Escolar Documentos
Profissional Documentos
Cultura Documentos
Developer’sGuide
Third Edition
Copyright © 2000-2002 by Digital Metaphors Corporation
ReportBuilder
Developer's Guide
Third Edition
Copyright © 2000-2002 by Digital Metaphors Corporation
i
CONTENTS
INTRODUCTION
The Basics
Report Creation .................................................................................................3
Select .................................................................................................................3
Design ................................................................................................................4
Process ..............................................................................................................4
Generation .........................................................................................................5
A Quick Test Spin
Overview ............................................................................................................7
Create a New Application ..................................................................................7
Create a Table, DataSource, and Data Pipeline Component ............................7
Create a Report and Connect it to the Data ......................................................7
Invoke the Report Designer ...............................................................................7
Place a Label Component in the Header Band ................................................7
Place a DBText Component in the Detail Band .................................................8
Preview the Report at Design-Time ...................................................................8
Preview the Report at Run-Time .......................................................................8
The Best Way to Learn ReportBuilder?
Start simple, then go to the next easy level. ....................................................11
Use the online help. .........................................................................................11
Use this manual. ..............................................................................................11
Run the examples; Study the examples; Know the examples. ........................11
Elements of the User Interface
The Report Designer .......................................................................................13
REPORTBUILDER FUNDAMENTALS
MAIN
Introduction
Overview ..........................................................................................................25
Report Layout ..................................................................................................25
Report Output ..................................................................................................25
Data Access .....................................................................................................25
Data Process ...................................................................................................25
The Delphi Components
DBPipeline .......................................................................................................27
BDEPipeline .....................................................................................................27
TextPipeline .....................................................................................................27
JITPipeline .......................................................................................................27
Report ..............................................................................................................27
Viewer ..............................................................................................................27
Archive Reader ................................................................................................27
Report Components
Overview ..........................................................................................................29
Memo ...............................................................................................................29
RichText ...........................................................................................................29
Label ................................................................................................................29
SystemVariable ................................................................................................30
Variable ............................................................................................................30
Image ...............................................................................................................30
Shape ..............................................................................................................30
TeeChart ..........................................................................................................30
BarCode ...........................................................................................................30
CheckBox ........................................................................................................30
DBText .............................................................................................................30
DBMemo ..........................................................................................................30
DBRichText ......................................................................................................31
DBCalc .............................................................................................................31
DBImage ..........................................................................................................31
DBBarCode ......................................................................................................31
DBTeeChart .....................................................................................................31
DBCheckBox ...................................................................................................31
Region .............................................................................................................31
SubReport ........................................................................................................31
CrossTab .........................................................................................................31
iv
Smart Layouts
Overview ..........................................................................................................33
StretchWithParent ............................................................................................33
ShiftWithParent ................................................................................................33
ShiftRelativeTo ................................................................................................33
StopPosition (for subreports) ...........................................................................33
BottomOffset ....................................................................................................33
OverFlowOffset ................................................................................................33
ReprintOnOverFlow .........................................................................................33
One Memo in the Detail Band ..........................................................................34
One Memo with a Shape Background .............................................................34
One Memo with Label Beneath .......................................................................35
Two Stacked Memos in the Detail Band ..........................................................35
Two Side-by-Side Memos with Labels Below.................................................. 36
Child SubReports in Fixed Positions ............................................................... 36
One Memo with Two Side-by-Side Memos Below ...........................................37
SubReports
Overview ..........................................................................................................39
Single Dataset ................................................................................................. 39
Master Dataset with Single Detail Dataset ......................................................40
Master Dataset with Nested Detail Datasets ...................................................40
Master Dataset with Multiple Independent Datasets .......................................41
Independent Datasets ......................................................................................41
Form Emulation
Overview ..........................................................................................................43
Single Page Forms ..........................................................................................43
Multi-Page Forms ............................................................................................45
DATA
Introduction
Overview ..........................................................................................................49
BDEPipeline .....................................................................................................49
DBPipeline ....................................................................................................... 49
TextPipeline ..................................................................................................... 49
JITPipeline .......................................................................................................49
Supplying Data ................................................................................................49
Controlling Data Traversal ...............................................................................50
BDE Support
Overview ..........................................................................................................53
Data Access .....................................................................................................53
BDE Alternatives
Overview ..........................................................................................................55
Advantage ........................................................................................................55
Apollo............................................................................................................... 55
Flash Filer ........................................................................................................55
Opus ................................................................................................................55
Titan .................................................................................................................55
ODBC Express ................................................................................................55
ODBC98 ..........................................................................................................55
InfoPower .........................................................................................................55
v
Text Files
The TextPipeline Component ..........................................................................57
The Field Editor ...............................................................................................57
Delphi Objects
Overview ..........................................................................................................59
JITPipeline .......................................................................................................59
Native Access to Proprietary Data
Overview ..........................................................................................................61
CODE
The Delphi Event Model
Overview ..........................................................................................................65
Significance ..................................................................................................... 65
Timing ..............................................................................................................65
AfterPrint ..........................................................................................................65
BeforePrint .......................................................................................................65
OnCancel .........................................................................................................66
OnPreviewFormCreate ....................................................................................66
Dynamic Configuration
Configure Reports During Generation .............................................................67
Font Color ........................................................................................................67
Concatenation ..................................................................................................68
Address Squeeze ............................................................................................69
Continued Group .............................................................................................70
Regions ............................................................................................................71
SubReports ......................................................................................................72
Performing Calculations
Overview ..........................................................................................................73
DBCalc component ..........................................................................................73
Variable component .........................................................................................73
Count ...............................................................................................................74
Count Master/Detail .........................................................................................75
Group Total ......................................................................................................76
Grand Total ......................................................................................................77
Cumulative Sum ..............................................................................................78
Conditional Group Total ...................................................................................79
Conditional Grand Total ...................................................................................80
Look Ahead Total .............................................................................................81
Creating Reports in Code
Coding a Report ...............................................................................................83
vi
DESIGN
The Report Designer
Design Tab ......................................................................................................89
Preview Tab .....................................................................................................89
Dialogs
Print Dialog ......................................................................................................91
Page Setup Dialog ...........................................................................................92
Groups Dialog ..................................................................................................93
Print to File Setup Dialog .................................................................................93
Data Dialog ......................................................................................................94
Toolbars
Overview ..........................................................................................................95
The Report Tree ..............................................................................................95
The Data Tree ..................................................................................................95
Standard Component Palette ..........................................................................96
Data Component Palette .................................................................................97
Advanced Component Palette .........................................................................98
Standard Toolbar .............................................................................................98
Edit Toolbar ..................................................................................................... 99
Format Toolbar ..............................................................................................100
Align or Space Toolbar ..................................................................................101
Size Toolbar ...................................................................................................102
Nudge Toolbar ...............................................................................................102
Draw Toolbar .................................................................................................103
Drag and Drop Support
Overview ........................................................................................................105
The Report Wizard
Overview ........................................................................................................107
Report Wizard: Create a Simple Report ........................................................107
Report Wizard: Create a Group-Based Report ..............................................110
vii
PRINT
Introduction
Generation .....................................................................................................115
Previewing
Print Preview ..................................................................................................117
Custom Printing Settings
Overview ........................................................................................................119
BinName ........................................................................................................119
Collation .........................................................................................................119
Copies ............................................................................................................119
DocumentName .............................................................................................119
Duplex ............................................................................................................119
Margins ..........................................................................................................119
Orientation .....................................................................................................119
PaperHeight & PaperWidth ............................................................................119
PaperName ....................................................................................................119
PrinterName ...................................................................................................119
Report Archiving
Overview ........................................................................................................121
Archiving a Report .........................................................................................121
Using the ArchiveReader ...............................................................................121
Print to ASCII Text
Overview ........................................................................................................123
Print directly to the ASCII text file ..................................................................123
Allow the end user to print to the ASCII text file ............................................123
Report Emulation Text File
Overview ........................................................................................................125
Print directly to report emulation text file ........................................................125
Allow the end user to print to a report emulation text file ...............................125
RTF, HTML, and Other Formats
Overview ........................................................................................................127
TExtraDevices ...............................................................................................127
PsRBExportDevices .....................................................................................127
viii
DEPLOY
Introduction
Overview ........................................................................................................131
Application Deployment .................................................................................131
Report Deployment ........................................................................................131
Report Templates
Overview ........................................................................................................133
File-based Templates ....................................................................................133
Database Templates ......................................................................................134
Loading and Saving Reports .........................................................................134
As an EXE
Overview ........................................................................................................135
Accessing the Delphi Library Path .................................................................135
As Packages
Overview ........................................................................................................137
ReportBuilder run-time packages ..................................................................137
International Language Support
Overview ........................................................................................................139
The Default Language ...................................................................................140
Custom Translations ......................................................................................141
ix
Data Dictionary
Overview ........................................................................................................159
FieldFieldNames ............................................................................................159
FieldPipeline ..................................................................................................159
TableFieldNames ...........................................................................................159
TablePipeline .................................................................................................159
Putting It All Together
Summary .......................................................................................................161
On-Line Help
Overview ........................................................................................................163
DATA
Introduction
Overview ........................................................................................................167
Dataview ........................................................................................................167
Query Wizard
Overview ........................................................................................................169
Query Wizard: Create a Simple Query-Based Dataview ..............................169
Query Designer
Overview ........................................................................................................173
Query Designer: Adding Search Criteria ......................................................173
Create a Group Sum ......................................................................................175
Concatenate Fields ........................................................................................178
Edit SQL ........................................................................................................180
Configuring DADE
Overview ........................................................................................................181
AllowEditSQL .................................................................................................181
DatabaseName ..............................................................................................181
DataDictionary ...............................................................................................181
SessionType ..................................................................................................181
SQLType ........................................................................................................181
UseDataDictionary .........................................................................................181
Database Product and SQL Type.................................................................. 181
Data Settings .................................................................................................182
DADE Architecture
Overview ........................................................................................................183
Basic Classes ................................................................................................183
Implementation classes .................................................................................184
xi
Extending DADE
Overview ........................................................................................................185
Dataview Templates ......................................................................................185
Dataview Template: The End User View .......................................................185
Dataview Template: The Implementation ......................................................187
Support for Non-BDE Database ....................................................................187
Classes ..........................................................................................................188
CODE
Introduction
Overview ........................................................................................................191
About RAP .....................................................................................................191
The Calc Workspace
Overview ........................................................................................................193
The Code Explorer .........................................................................................194
The Code Editor .............................................................................................196
Message Window ..........................................................................................197
The Code Toolbox .........................................................................................197
Writing RAP Code
Programs in RAP ...........................................................................................201
Coding an Event Handler ...............................................................................201
Compiling Event Handlers .............................................................................202
Declaring Local Variables ..............................................................................202
Declaring Local Constants .............................................................................202
Declaring Global Variables ............................................................................202
Declaring Global Constants ...........................................................................203
Declaring Global Procedures and Functions .................................................203
Procedure and Function Parameters .............................................................204
Calling Procedures and Functions .................................................................204
Configuring RAP
End User Configurations ................................................................................205
Extending RAP
RAP Pass-Through Functions .......................................................................209
Adding Functions to the Code Toolbox ..........................................................209
Adding Classes and Properties via RTTI .......................................................210
Debugging RAP Code
CodeSite Support ..........................................................................................211
Using the CodeSite Functions .......................................................................212
Conditionally Compiling CodeSite Support ....................................................213
DESIGN
The Report Explorer
Report Explorer Toolbar ................................................................................217
xii
PRINT
End-User Options
Overview ........................................................................................................221
End-User Applications ...................................................................................221
DEPLOY
Summary
Overview ........................................................................................................225
Application Deployment .................................................................................225
Report Deployment ........................................................................................225
xiii
REPORT TUTORIALS
Creating a Report Via the Data Tree
Overview ........................................................................................................229
Create a Tutorial Folder .................................................................................229
Create a New Application ..............................................................................229
Create a Table, DataSource, and DataPipeline Component .........................230
Create a Report and Connect it to the Data ..................................................230
Invoke the Report Designer and Set the Paper Orientation ..........................230
Set the Header Band Height to 1 inch ...........................................................230
Create Labels in the Header Band ................................................................231
Use the Data Tree to Lay Out the ..................................................................232
Customer Information ....................................................................................232
Adjust the Layout ...........................................................................................233
Add a TimeStamp ..........................................................................................234
Add Page Numbers .......................................................................................234
Preview the Report at Run-time .....................................................................235
Creating a Report Via the Report Wizard
Overview ........................................................................................................237
Create a New Application ..............................................................................237
Create a Table, DataSource, and DataPipeline Component .........................238
Create a Report and Connect it to the Data ..................................................238
Invoke the Report Designer and Access the Report Wizard .........................238
Use the Report Wizard to Lay Out a Tabular Style Report ............................238
Preview the Report ........................................................................................239
Set the Report to Two-Pass Mode .................................................................239
Save the Report Layout to a Template File ...................................................240
Use the Report Wizard to Lay Out a Vertical Style Report ............................240
Modify the Report Layout to Contain Columns ..............................................241
Save the Report Layout to a Template File ...................................................241
Add the Run-Time Interface ...........................................................................242
Components ..................................................................................................242
Code the Event Handlers ...............................................................................243
Compile and Run the Application ..................................................................244
A Simple Report the Hard Way
Overview ........................................................................................................247
Create a New Application ..............................................................................247
Create a Table, DataSource, and DataPipeline Component .........................248
Create a Report and Connect it to the Data ..................................................248
Invoke the Report Designer and Set the Paper Orientation ..........................248
Lay Out the Customer List Title Label in the Header Band ...........................248
Lay Out the Company Title Label in the Header Band ..................................249
Create Labels for the Header Band ...............................................................250
Complete the Header Band Layout ...............................................................250
Lay Out the Detail Band .................................................................................251
Align the Header Band Labels Vertically .......................................................252
Align the Header Band Labels with the Detail Band DBText Components ....252
Set PrintDateTime .........................................................................................252
Set Page Numbers ........................................................................................253
Preview the Report at Run-Time ...................................................................253
xiv
Creating a Crosstab
Overview ........................................................................................................349
Create a New Application ..............................................................................349
Create a Query, DataSource, and DataPipeline Component ........................349
Create a Report .............................................................................................350
Design the Crosstab ......................................................................................351
Add Additional Values to the Crosstab ..........................................................351
Set the Format of the Values .........................................................................351
Calculate Totals by State ...............................................................................352
Lay Out the Header Band ..............................................................................352
Set Pagination ...............................................................................................352
Use Repeated Captions................................................................................. 352
xix
RAP TUTORIALS
Concatenating Fields
Overview ........................................................................................................355
Create a Tutorial Folder .................................................................................355
Create a New Application ..............................................................................355
Create a DataView .........................................................................................355
Layout the Report ..........................................................................................356
Navigate the Calc Workspace .......................................................................356
Add the Concatenation Code .........................................................................357
Compile and Preview .....................................................................................358
Save the Report .............................................................................................358
Load the Report .............................................................................................358
Color-Coding Components
Overview ........................................................................................................359
Open the Demo Project .................................................................................359
Enable DetailBeforePrint ...............................................................................359
Add Local Variables .......................................................................................360
Preview and Save ..........................................................................................361
Dynamic Duplexing
Overview ........................................................................................................363
Enable RAP ...................................................................................................363
Create a New DataView ................................................................................363
Create Report Layout ....................................................................................364
Compile and Preview .....................................................................................365
Adding Functions to RAP
Overview ........................................................................................................367
Create a New Unit .........................................................................................367
Edit Uses Clause ...........................................................................................367
Add TraSystemFunction Descendent for Category .......................................368
Add New Function Class ...............................................................................369
Implement ExecuteFunction ..........................................................................369
Implement GetSignature ................................................................................369
Implement HasParams ..................................................................................370
Add Initialization .............................................................................................370
Add myRapFuncs to a Project .......................................................................371
See ApplicationFilename in Code Toolbox ....................................................371
Add ApplicationFilename to Code .................................................................372
xx
APPLICATION TUTORIALS
Building a Reporting Application
Overview ........................................................................................................401
Create a New Application ..............................................................................401
Create a ListBox and Preview Button on the Main Form ...............................401
Add a Form to the Project ..............................................................................402
Create an Ancestor Form Class ....................................................................402
Make the Tutorial Report Form a Descendant of TrbReportForm .................403
Populate the List Box in the OnCreate Event of the Main Form ....................404
Code the LaunchReport Procedure in the Main Form ...................................404
Hook the LaunchReport Procedure to the ListBox and Preview Button ........405
Create a Customized Print Preview Form .....................................................406
Add the Customized Print Preview Form to your Project ...............................406
Building an End-User Reporting Application
Overview ........................................................................................................409
Create the Folder Table .................................................................................409
Create the Item Table ....................................................................................410
Create a New Application ..............................................................................411
Create Data Access Components for the Folder Table .................................411
Create Data Access Components for the Item Table ....................................411
Create the ReportBuilder Components ..........................................................412
Configure the Designer Component ..............................................................412
Compile and Run the Application ..................................................................412
Create New Folders .......................................................................................413
Adding Data Dictionary Support to the End-User Application
Overview ........................................................................................................415
Create the Field Data Dictionary Table ..........................................................415
Create the Table Data Dictionary Table ........................................................416
Create the Join Data Dictionary Tables .........................................................416
Open the End-User Application .....................................................................417
Create Data Access Components for the Tables ..........................................417
Create Data Access Components for the Field Table ...................................417
Create Data Access Components for the Join Table .....................................418
Create the Data Dictionary Component .........................................................418
Populate the Tables .......................................................................................418
Configure the Designer Component ..............................................................419
Compile and Run the Application ..................................................................419
Create a Simple Query ..................................................................................419
Create a Simple Report .................................................................................420
Customizing the Report Explorer Form
Overview ........................................................................................................421
Open the End-User Application .....................................................................421
Create a New Report Explorer Form .............................................................421
xxii
The Basics 3
A Quick Test Spin 7
The Best Way to Learn ReportBuilder 11
Elements of the User Interface 13
Working with the Report Designer 15
Reporting Basics 19
The Basics
INTRODUCTION 3
The Basics
Welcome to the ReportBuilder Developer's Guide. ReportBuilder handles the Generate step for you,
This guide is written by ReportBuilder engineers and with the help of this guide, you can certainly
for Delphi developers. The concepts and practical master the Select, Design, and Process activities.
elements of reporting with RB will be revealed First, let's get a better handle on these rather
throughout this book, and the tutorials will trans- abstract concepts.
form the abstract concepts into concrete, useful
Select
reports and applications.
Your data is probably not locked into disposable
Report Creation documents; it's organized (one way or another) as
Report creation with ReportBuilder can be divided data. When you have data, you generally have a
into four main activities: database. Organized data is the first key to creating
recyclable documents. ReportBuilder expects data
Report Creation Activities to take a tabular format. Yes, you can create
reports based on less structured data, but in general
it is most advantageous to have the data organized
Select Design in a table. Here's an example:
Process Generate
Design Process
Once data has been selected, you can begin design- When you create a layout, you are telling Report-
ing your report. You do this by creating a layout. Builder exactly how you want the document to
A layout is a combination of objects that describe look. But what if your document is so complex
how the document should look. that you can't design a layout to describe it?
Though ReportBuilder layouts are quite flexible
and powerful, as you will soon see, even the most
flexible layout is still fixed. The Process activity
of document creation allows you to provide addi-
tional instructions to ReportBuilder regarding how
the document should be created. Therefore, you
can change the report layout as the document is
generating. You can also use the processes to for-
mat data and perform calculations. Processes are
created using ReportBuilder's native language.
The language is called RAP (for Report Applica-
tion Pascal). It is easy to learn and fun to use, espe-
This is the Report Designer. As you can see, it
cially when you see the cool effects you can create
looks like many of the other Windows applications
with it. For example, you can use RAP to combine
you're used to working with. The big difference is
the First and Last Name fields of a contact so the
that the Report Designer does not contain a docu-
data is easier to read in the report, or to calculate a
ment; it contains a layout. The layout can be used
weighted average to appear in the summary section
to generate many different documents, all based on
at the end of a report.
the data you've selected. The white rectangular
areas with the gray bars below are called bands. Most reports do not require a process, so don't
This report has a Header, Detail, and Footer band. worry about whether or not you can master this
When ReportBuilder generates a document from activity. This guide will show you how to do sim-
this layout, the objects in the Header band will ple calculations and even some fairly complex
appear at the top of each page. The objects in the stuff, if you're interested. Just remember that Pro-
Footer band will appear at bottom of each page. cess is the place you go when you can't get a report
And the objects in the Detail band will repeat down to look exactly the way you want and all other ave-
the page until no more page space is available, at nues seem to be closed.
which point a new page will be started. The Detail
band prints once for each row of your data selec-
tion. This is how a document is created from the
layout. You can generate a different document
from the same layout by simply changing your data
selection.
The Basics
INTRODUCTION 5
Generation
Generation is what happens when you click on the
'Preview' tab in the Report Designer and see the
generated document in the print preview window.
The document will either look right, or it won't. If
it doesn't look right, then it's time to return to the
Select, Design, or Process area and make the
changes necessary to get the document generating
properly. Sometimes you learn the most by tinker-
ing with a data selection or layout and then check-
ing to see how ReportBuilder generates the
document differently.
3 Configure the Table component: 2 Size and Move the Report Designer window so
that the Object Inspector is visible.
DatabaseName DBDEMOS
Name tblCustomer Place a Label Component in the
TableName CUSTOMER.DB Header Band
1 Right-click over the white space of the header
4 Double-click the Active property in the Object
band and access the Position... dialog.
Inspector.
2 Set the Height value to 0.9167 and click the OK
5 Add a DataSource component to the form.
button. The header band should expand in height.
6 Configure the DataSource component:
DataSet tblCustomer
Name dsCustomer
A Quick Test Spin
8 INTRODUCTION
NOTE: You can also change the height of the Place a DBText Component in the Detail
header band by dragging the gray divider that Band
appears below the white space of the header band.
1 Click the DBText component icon on the
This method is quick and easy, but not as precise.
Report Designer component palette.
3 Click the Label component icon on the 2 Click in the detail band. A DBText component
Report Designer component palette. will be created.
4 Click on the left side of the header band. A 3 Locate the two drop-down lists at the upper left
label will be created in the header band and will corner of the Report Designer. The list on the left
become the current selection in the Object Inspec- contains a list of data pipelines. It should default to
tor. the Customer data pipeline since this is the data
pipeline for the report. The list on the right con-
5 Locate the Edit box at the upper left corner of
tains a list of fields for the currently selected data
the Report Designer.
pipeline.
6 Select the text inside it and replace it with Com-
4 Select the Company field from the field list.
pany.
'Kauai Dive Shoppe' should be displayed in the
7 Use the font controls to set the font: DBText component.
Font Name Times New Roman 5 Use the font controls to configure the font:
Font Size 12
Font name Times New Roman
Font Style Bold & Italic
Font size 10
NOTE: The font controls appear to the right of the Font color Black
Edit box and provide the following functions:
Preview the Report at Design-Time
• Font Name drop-down list 1 Click the Preview tab in the Report Designer.
• Font Size drop-down list You should get a four-page report.
• Bold
Preview the Report at Run-Time
• Italic
1 Close the Report Designer.
• Underline Font Style
• Text Alignment 2 Select the Standard tab of the Delphi component
• Font Color palette.
• Highlight Color
3 Add a Button component to the form.
A Quick Test Spin
INTRODUCTION 9
4 Configure the Button component:
Name btnPreview
Caption Preview
Start simple, then go to the next easy key (the appropriate help topic should automati-
level. cally display), and by searching the help index for
This is the secret of champions. If you work your a topic. The help contains over 1,500 topics writ-
way from one easy level to the next, then you can ten for the ReportBuilder developer. It's worth
end up a very skillful developer. If you jump in at using often.
the top, you can end up quite overwhelmed. When
Use this manual.
you begin to use ReportBuilder, do the easiest
This manual is designed to give you hands-on
report you can imagine. Better yet, complete the
experience with report building and conceptual
'Quick Test Spin' section of this manual: it will
background material that should allow you to bet-
show you how to build a simple report (and it will
ter utilize ReportBuilder.
only take about 5 minutes). I know some of you
will read this and say, “But I don't have time for Run the examples; Study the examples;
that. I need to know if ReportBuilder will do my Know the examples.
real reports.” My answer is that you don't have The examples that come with ReportBuilder are an
time to not do it. While you burn away hours invaluable part of the product. Not only do they
attempting to complete real reports, you will be look nice and showcase many of the product's fea-
learning from experience, which is not a bad exer- tures, they also show you how to build different
cise in and of itself, but this approach is fairly types of reports. Many of the examples were put
awful when compared with learning from the mas- together in direct response to questions developers
ter. Give yourself at least 2-3 hours to go through have posed about how to use ReportBuilder. For
the tutorials. They have been ordered from simple instance, one example shows you how to compile
to complex. The first few tutorials are the easiest; and use a report as a DLL. Study the examples
the last few are the most difficult. This gradient thoroughly and use them as a reference when you
approach should allow you to build up your are trying to build a report and not quite sure how
ReportBuilder skills with minimum frustration. to put all the pieces together. If you're having a
Regardless of whether you decide to use this man- problem getting something to work, refer to the
ual or not, you should remember this important examples and see whether there is an example of a
concept: start simple, then go to the next easy level. similar report. The examples are located in the
\RBuilder\Demos directory.
Use the online help.
The help is accessible in three different ways: by NOTE: If you have completed all of the tutorials in
accessing the Help | Contents menu option from this manual, you will be able to pick the examples
the Delphi main menu (ReportBuilder Reference apart and identify key techniques in short order.
should be listed in the table of contents), by select-
ing a component or property and clicking the F1
Elements of the User Interface
INTRODUCTION 13
The Report Designer click in the white space of a band. There are three
The Report Designer is your key to productivity component toolbars: Standard, Data, and
when creating reports in Delphi. The Report- Advanced. Use the Standard components to create
Builder engineers have made every effort to ensure text, lines, shapes, memos, richtext, etc. Use the
that the Report Designer interface is consistent Data components when you want to display the
with other Windows programs you've used before. data from a database. Use the Advanced compo-
The major areas of the Designer are listed below. nents when you need to create more complex
reports using subreports, regions, or crosstabs.
Component Palette Toolbars
These toolbars are used to create new components.
To create a component, click on the icon and then
Component
Toolbars
Rulers
Detail band
Footer band
Status Bar
Elements of the User Interface
14 INTRODUCTION
Edit Toolbar
The Edit toolbar allows you to set the most impor-
tant property for a given component. For example,
when a Label component is selected, an edit box
appears that allows you to set the Caption. When a
DBText component is selected, two drop-down
lists appear that allow you to set the Data Pipeline
and the DataField.
Format Toolbar
This toolbar appears to the right of the Edit toolbar.
It's used to configure the font of textual compo-
nents and to control component layering via the
Bring to Front and Send to Back commands.
Rulers
The horizontal ruler allows you to determine a
component's position on the page. The vertical
ruler for each band allows you to determine a com-
ponent's position relative to the starting print posi-
tion of the band.
All Bands
Notice the gray rectangular area below the white
space of each band. This area is draggable, and it
allows you to redefine the height of the band.
Status Bar
The Status Bar shows messages and object posi-
tions.
Working with the Report Designer
INTRODUCTION 15
The Layout tab of the Data Tree contains many set- Style drop-down listControls whether the
tings which you can use to customize the drag-and- DBTextand Label components are oriented in a
drop capabilities of the Data Tree. columnar or stacked fashion .
Reporting Basics
REPORTBUILDER
FUNDAMENTALS
Main 25
Data 49
Code 65
Design 89
Print 115
Deploy 131
MAIN
Introduction 25
The Delphi Components 27
Report Components 29
Smart Layouts 33
SubReports 39
Form Emulation 43
Introduction
REPORTBUILDER FUNDAMENTALS - MAIN 25
MAIN
Introduction
Data Process
Data process refers to the calculation of intermedi-
ate results based on data and the modification of
the report layout as it generates.
Introduction
26 REPORTBUILDER FUNDAMENTALS - MAIN
Delphi Components
DBPipeline Report
Used for accessing data via the BDE, third-party The main component. Double-click to invoke the
BDE replacement products, or TDataSet descen- Report Designer. Assign the DataPipeline prop-
dants. The DBPipeline is connected via the Data- erty so that the report can traverse data. Assign the
Source property. DeviceType property to control where the output
of the report is directed. Call Report.Print from
BDEPipeline Object Pascal to print the report or launch the Print
In previous versions of ReportBuilder, the BDE- Preview Form.
Pipeline was used for accessing data via the BDE.
Though it has been replaced by the DBPipeline, it Viewer
has been retained for backward capability. This object is rarely used because you can replace
ReportBuilder's built-in print preview form with
TextPipeline your own customized version very easily (check
Used to access comma, tab, and fixed-length the Building a Reporting Application tutorial). If
record text files. Set the FileName property to you must use this component, an example is pro-
specify the file. Double-click on the component to vided in \RBuilder\Demos\Reports.
define the field structure.
Archive Reader
JITPipeline After you print a report to an archive file (.raf
Used to access any non-structured data stored in extension), you can read and preview the file via
Delphi objects or other sources. Provides total this component. Just assign the ArchiveFileName
control over the data-access process. Set the Ini- to the file and call the Print method. In terms of
tialIndex and RecordCount properties and code the displaying a report, this component works the same
OnGetFieldValue event to utilize this component. as the Report component.
Double-click on the component to define the field
structure.
Report Components
REPORTBUILDER FUNDAMENTALS - MAIN 29
Report Components
Overview Memo
The ReportBuilder Report Component Library Used to print multiple lines of plain text in a report.
(RCL) provides a powerful, robust set of compo- To set the value, assign a string list to the Lines
nents that have been designed and optimized specif- property. To dynamically resize the memo during
ically for the reporting environment. The library printing, set the Stretch property to True. Use the
includes over 20 components that enable you to put ShiftRelativeTo property to define dynamic rela-
all types of data in your reports: Lines, Shapes,Text, tionships with other stretchable objects.
Memos, RichText, Images, Charts, and BarCodes.
Advanced components such as Regions, SubRe- RichText
ports, and CrossTabs can be used to elegantly model Used to print formatted text. To set the value,
complex reports. assign the RichText property or use the
TeeChart
Used to display standard (non-data-aware) Tee-
Charts. This component enables you to use Tee-
Chart inside the Report Designer. You can access
the TeeChart editor via a popup menu.
BarCode
Used to render barcodes. The string value assigned
SystemVariable to the Data property is encoded based on the Bar-
Used to display common report information such CodeType. If the data to be encoded is in a data-
as page number, page count, print date and time, base, use DBBarCode. The following symbologies
date, time, etc. The type of information displayed are supported: Codabar, Code 128, Code 39, EAN-
is controlled by the VarType property. The format 13, EAN-8, FIM A,B,C, Interleaved 2 of 5, Post-
is controlled by the DisplayFormat property. Net, UPC-A, UPC-E.
Variable CheckBox
Used for calculations via an Object Pascal event
Displays a checkbox using the WingDings font.
handler assigned to the OnCalc event or a RAP
event handler assigned to the OnCalc event. DBText
Access the Calculations dialog (via the speed Used for displaying values from all types of data-
menu) or the Calc tab of the Report Designer to base fields. Use the DisplayFormat property to
code a RAP calculation for this component. format the value.
Image DBMemo
Used to display bitmaps and windows metafiles in Used to print plain text from a memo field of a
reports. Assign the Picture property of this compo- database table. This control will automatically
nent in order to place an image in your report. Use word-wrap the text. Set the Stretch property to
the Report Designer's built-in picture dialog to load True and the component will dynamically resize to
images at design-time. print all of the text. Use the ShiftRelativeTo prop-
erty to define dynamic relationships with other
Shape
stretchable objects.
Use this component to print various shapes
(squares, rectangles, circles, ellipses). Set the
Shape property to select a type of shape. Use the
Brush and Pen properties to control the color and
border respectively.
Report Components
REPORTBUILDER FUNDAMENTALS - MAIN 31
Report Components - cont.
DBRichText DBTeeChart
Used to print formatted text from a memo or Allows data-aware TeeCharts to be placed within a
BLOB field of a database table. This control will report.
automatically word-wrap the text. Set the Stretch
property to True and the component will dynami- DBCheckBox
cally resize to print all of the text. Use the Displays a checkbox based on the value of the field
ShiftRelativeTo property to define dynamic rela- specified in the DataField property. Can be used
tionships with other stretchable objects. with a Boolean field (or any other type of field via
the BooleanTrue, BooleanFalse properties).
DBCalc
Used for simple database calculations (Sum, Min, Region
Max, Count and Average). The value can be reset Used to logically group components together. Use
when a group breaks using the ResetGroup prop- the ShiftRelativeTo property to move the region in
erty. relation to another dynamically resizing compo-
nent (such as Memo, RichText, or child-type Sub-
DBImage Report).
Used to print bitmaps or windows metafiles, which
are stored in a database BLOB field. SubReport
Used to handle multiple master details, create side-
DBBarCode by-side reporting effects, and hook reports together
Used to render barcodes based on the BarCode- as one. If you need a report to print within the con-
Type and the value supplied via the DataField text of a band, use a child-type subreport. If you
property. The following symbologies are sup- need to hook reports together, use a section type
ported: Codabar, Code 128, Code 39, EAN-13, subreport. The PrintBehavior property determines
EAN-8, FIM A,B,C, Interleaved 2 of 5, PostNet, the subreport type.
UPC-A, UPC-E.
CrossTab
Used to present summarized data in a grid format.
Smart Layouts
REPORTBUILDER FUNDAMENTALS - MAIN 33
Smart Layouts
Overview BottomOffset
ReportBuilder allows you to create highly dynamic Used to create white space between multiple
report layouts. The SubReport, Memo, RichText, stretching objects that have been linked together
and Region components have the ability to expand using the ShiftRelativeTo property.
or contract to accommodate the information they
OverFlowOffset
contain. There are a host of properties designed to
Controls the position where a stretching compo-
keep your reports looking good in the variety of sit-
nent will begin printing when it overflows to addi-
uations created by these dynamic components.
tional pages. This property can be used to print an
StretchWithParent object at a different starting position when it over-
Allows a shape or line to expand or contract based flows onto additional pages.
on the change in height of the band or region in
ReprintOnOverFlow
which it is contained.
Used to print non-stretching components when
ShiftWithParent stretching components are printing on additional
Allows any non-stretching component to move up pages.
or down based on the change in height of the band
or region in which it is contained.
ShiftRelativeTo
Used to specify the vertical positioning that should
take place between multiple stretching components
in a band.
One Memo in the Detail Band One Memo with a Shape Background
Design Preview
Design Preview
Here we have a single memo component in the
detail band. The memo's Stretch property has been Here we have a single memo in the detail band
set to True. Each time the detail band prints, the with a shape behind it. The shape has the Stretch-
height of the memo is recalculated based on the WithParent property set to True. The parent, in
amount of text it contains. As a result, the memo this case, is the detail band. When the band gener-
may either grow or shrink in size and the detail ates, the memo will stretch based on the text it con-
band will grow and shrink with it. The memo may tains; the band will resize to accommodate the
contain so much text that it cannot fit on a single memo, and the shape will resize based on the
page. In this case, the memo will print on addi- change in height of the band. This stretching and
tional pages until it is complete. In ReportBuilder, resizing creates the effect of a border and back-
this condition is referred to as overflow. Both the ground for the memo. If the memo overflows onto
memo and band components have a boolean Over- additional pages, we can also instruct the shape to
Flow property which can be checked while the print by setting the shape's ReprintOnOverFlow
report is generating to determine if the memo is property to True.
printing on an additional page.
Smart Layouts
REPORTBUILDER FUNDAMENTALS - MAIN 35
One Memo with Label Beneath Two Stacked Memos in the Detail Band
label
memo
Design Preview
detail band
report report detail band
subreport
subreport
detail band
memo memo memo memo
subreport subreport
region region subreport subreport
label label
region
region subreport
label subreport
label
Design Preview
Design Preview
Here we have two memos in the detail band, each This report emulates a form that contains informa-
set to stretch. When the report generates, the band tion in fixed rectangular areas of the page. We can
will grow or shrink to accommodate the memo that get the report to 'fill out' this form by placing child-
contains the most text. Each memo has an associ- type subreports at the beginning of each rectangu-
ated label below it. We want the labels to shift in lar area and setting the StopPosition property equal
relation to the memo above. In order to accom- to the bottom of the rectangular area.
plish this, we place the labels in a region and then
set the region's ShiftRelativeTo property to point at
the memo above. Now when the report is gener-
ated, each label shifts in relation to the associated
memo.
Smart Layouts
REPORTBUILDER FUNDAMENTALS - MAIN 37
One Memo with Two Side-by-Side
Memos Below
report report
detail band
detail band
memo memo
region
memo memo
region
memo memo
Design Preview
SubReports
Master Dataset with Single Detail Master Dataset with Nested Detail
Dataset Datasets
customer customer
subreport subreport
subreport
order order
subreport
product
vendor
subreport1
order item vendor detail band
subreport2
subreport1 product
subreport2
Form Emulation
2 How will the data that fills-out the form be gen- 2 Add a page style to the report. Place all format-
erated? ting for the form in the page style. Place the data-
aware controls in the bands as you would when
The first issue is resolved by using either a page-
building a normal report. This approach yields a
sized band within the report or by utilizing a page
variable number of records per form, depending on
style. A page style can be designed just like a
the height of the bands. In this approach, the detail
band, but generate as a background to the bands of
band is used to fill-out the form. The following
the report.
diagram shows how a detail band can fill-out a
The second issue is resolved by either using simple page style.
data-aware components or by using more complex
report report
region or subreport components.
detail band detail band & page style
dbtext
In ReportBuilder, there are several approaches that dbtext
label
label
dbtext
dbtext
memo shape
memo
page style
label
label
shape
shape
Design Preview
Form Emulation
44 REPORTBUILDER FUNDAMENTALS - MAIN
3 Expand the detail band to the printable height of When you have a form in a WMF image, the end
the page. Hide the header and footer band, and user gets an excellent print preview capability. If
place all form formatting in the detail band. Place you are printing on pre-printed forms, you can set
child-type subreports in different areas of the form the visible property to False when the report is sent
where a table or particular source of data is needed to the printer. In this way you can provide a filled-
to fill-out that part of the form. Place data-aware out form in the print preview window, but only the
components in areas of the form where the main text necessary to fill-out the form is actually sent to
data pipeline supplies the data. This placement the printer.
yields the most flexible and powerful form emula-
You can convert a scanned form to a windows
tion solution, but is only needed when multiple
metafile image (WMF) via a product such as
datasets are used. The following diagram shows
Transform Suite, by MIPS.
subreports filling out a form in the detail band.
report report
detail band
detail band
subreport
subreport
subreport subreport
subreport subreport
subreport
subreport
Design Preview
report engine), and then return control to the parent subreport 1 page 4: subreport 1
subreport 2 page 5: subreport 2
report. One special behavior of section-type subre- subreport 3 page 6: subreport 3
…continuing in sets of 3 until the
ports is that the parent report generates no pages last record is reached
DATA
Introduction 49
BDE Support 53
BDE Alternatives 55
Text Files 57
Delphi Objects 59
Native Access to Proprietary Data 61
Introduction
REPORTBUILDER FUNDAMENTALS - DATA 49
DATA
Introduction
BDEPipeline
Each time a data-aware report component prints, it
In previous versions, the BDEPipeline was used to
uses this approach to retrieve the data from the data
access data via the Borland Database Engine
pipeline. Data-aware report components have two
(BDE). Though it has been replaced by the
properties that determine the data they will
DBPipeline, it has been retained for backward
retrieve: DataPipeline and DataField. Once these
capability.
two properties are assigned, the data-aware compo-
DBPipeline nent has the ability to retrieve data directly from
Used to access data via the BDE, a BDE replace- the data pipeline, independent of the report in
ment product, or TDataSet descendant. which the data-aware component resides.
TextPipeline
Used to access data in ASCII text files.
JITPipeline
Just-In-Time pipeline for accessing data in Delphi
objects.
1 To supply data
Controlling Data Traversal component or report), then the report will not
The second purpose of the data pipeline is to con- work. Therefore, the report must be assigned to a
trol data traversal. Data traversal is the act of mov- data pipeline and each data-aware component must
ing from the first record of the data to the last be assigned to a data pipeline and a datafield.
record. When a report is printed, the report engine
customer table
steps:
detail band
5 Gives the detail band the opportunity to print. dbtext: contact dbtext: phone
Erica Norman 808-555-0269
Let's take this example further and say that you let
the user select multiple records from the database
grid. You then want the report to contain only the
selected records. In this case we can assign the
Bookmarks from the grid using the AddBookmark
method of the data pipeline. When the report
prints, the data pipeline will traverse only those
records that are in the list of bookmarks and only
those records will appear in the report. Essentially,
the engine makes the same traversal requests of the
data pipeline for every report, but it is the data
pipeline that controls how the data is actually tra-
versed.
BDE Support
REPORTBUILDER FUNDAMENTALS - DATA 53
BDE Support
Data Access
In Delphi, data access via the BDE can be accom-
plished using a TTable or TQuery component. A
TDatasource component is then connected to the
table or query. A data-aware component can then The value is displayed in a ReportBuilder data-
be connected to the datasource. The following aware memo component. You may notice that
screen-shot shows a field value being retrieved into only the first line of the memo is shown in the
a data-aware memo component. ReportBuilder Report Designer. This is due to the
fact that when the report generates, the memo com-
ponent will recalculate the height based on the text
it contains. Therefore, there is no reason to specify
the height of the memo in the report layout, as it
will automatically resize on the generated page.
BDE Alternatives
REPORTBUILDER FUNDAMENTALS - DATA 55
BDE Alternatives
Overview Titan
The Borland Database Engine (BDE) is what Del- by Reggatta Systems, Inc.
phi uses to access desktop and client/server data- Several products are offered that provide access to
bases. However, there are a number of BDE BTrieve, MS Access, and SQLAnywhere.
replacement products available. ReportBuilder's
DBPipeline can also be used with these products or ODBC Express
any database that supports Delphi's TDataSource. by DataSoft Pty.
Some of the more popular Delphi database add-on Provides ODBC access without the overhead of the
products used by our customers are listed below. BDE.
Advantage ODBC98
by Extended Systems by Kosta Corriveau
Provides access to .DBF files. Desktop and high Provides ODBC access without the overhead of the
performance Client/Server versions are available. BDE.
ReportBuilder allows the Advantage TDataSet
InfoPower
descendant to plug in directly. The high-perfor-
by Woll2Woll Software
mance, low maintenance features of the Advantage
Database Server and the extremely well-designed Data access components are used to filter, search,
architecture of ReportBuilder make this combina- etc. Although InfoPower is not a database engine
tion an excellent client/server reporting solution. like the products above, the components are widely
used by Delphi developers everywhere.
Apollo
by Luxent Software
Provides access to .DBF files.
Flash Filer
by Turbo Power Software
Compact database written in Object Pascal.
Opus
by Opus Software GmbH
Provides access to MS Access database files.
Text Files
REPORTBUILDER FUNDAMENTALS - DATA 57
Text Files
Delphi Objects
Overview JITPipeline
Data pipelines present a structured set of data to a The JITPipeline provides a set of events that, when
report. This structure takes the form of records and coded properly, allow reports to print from any
fields. The report engine expects operations like source of data referenced by the event handlers.
open, first, next, and last to provide a certain The following diagram shows a JITPipeline that is
response from the data pipeline. The data-aware assigned to event handlers referencing a standard
components within the report expect field values to Delphi string grid. In the report, data-aware com-
be retrievable by simply passing a field name to the ponents are created just as they would be for any
data pipeline. In the DBPipeline component, this other database report - by assigning field names
functionality is implemented by calling the meth- from the JITPipeline to the data-aware controls in
ods of a TDataSet object. However, this is not the the report. This results in a clean, maintainable
only way a data pipeline can provide the necessary implementation. If you later decide to provide data
data access functionality to a report. The JITPipe- to the report via a text file or database table, you
line (JIT stands for Just-In-Time) triggers events to can simply swap out the JITPipeline with a new
accomplish the same results as the DBPipeline. pipeline of the correct type.
string grid
contact phone city
OnGetFieldValue
report
detail band
dbtext: contact dbtext: phone
Erica Norman 808-555-0269
Native Access to Proprietary Data
REPORTBUILDER FUNDAMENTALS - DATA 61
Overview
If you have a considerable amount of data in a pro-
prietary format, and many reports need to be cre-
ated based on this data, the highest level of
maintainability and ease of use will be provided by
a custom data pipeline component. This type of
component can be created by descending from the
TppCustomDataPipeline class and implementing
the necessary methods. The end result of such an
effort will be a new data pipeline component that
can be installed into the Delphi IDE and used on
the same basis as the other data pipelines that are
provided with ReportBuilder. The object model
for the ReportBuilder DataPipeline classes is
shown below:
DataPipeline
CustomDataPipeline
CODE
OnCancel
When printing to the printer, OnCancel fires when
the Cancel button of the cancel dialog is clicked. It
allows cancelled print jobs to be tracked.
OnPreviewFormCreate
This event is instantiated when the Print Preview
form has been created, but before it has been dis-
played. It allows the Print Preview form to be con-
figured.
Dynamic Configuration
REPORTBUILDER FUNDAMENTALS - CODE 67
Dynamic Configuration
Code Setting the color of a numeric DBText component based on the sign
Concatenation
This event handler is assigned to the OnPrint event
of a Label component. When the component
prints, the current value of the FirstName and Last-
Name fields are retrieved. If the FirstName has a
length greater than zero, it is included in the cap-
tion. The local variables used here are prefixed
with 'ls', which stands for local string.
Continued Group
This event handler is attached to the OnPrint event
of a label in the detail band of the report. The 'if'
statement checks to see if this is the first page of
the group and the first detail band of the page. If it
is not the first page of the group, the group is print-
ing on additional pages. In this case, the label is
made visible. The label's caption is set to 'Contin-
ued...'; this creates the effect of labeling detail lines
that print on additional pages for the same group.
SubReports
This event handler is associated with a master/
detail report. The report contains a subreport that
prints the detail. This report resides on a form with
a button captioned 'Hide Detail'. When the button
is clicked, the event handler toggles the value of
the subreport's visible property and then prints the
report. As a result, the report is either a high-level
summary or a full-detail listing; thus, the report
provides the functionality of two reports from only
one layout.
Count
To number the detail bands, place a DBCalc com-
ponent in the detail band of a report. Right-click
over the component and select the Calculations...
menu item. A dialog will be displayed. Set the
calculation type to Count and click OK. When you
return to the Report Designer, the DBCalc will
contain this caption: 'Count(*)'. There is no need
to select an individual field for the DBCalc because
the Count function does not require one. Preview
the report. Each detail band will be numbered as
shown below.
Group Total
Report group totals can be easily calculated by
placing a DBCalc in the group footer band. The
ResetGroup is automatically assigned when a
DBCalc is placed in a group band. Thus, each time
the group breaks, the group total will reset to 0.
Cumulative Sum
To calculate a cumulative sum in the detail band,
add a DBCalc in the detail band and assign it to the
appropriate data pipeline and field.
1 Create a group.
Using a DBCalc and a variable to display a group total at the beginning of a group
Coding a Report The types that are being used from each unit are
A report layout is composed of a set of compo- documented in the comments of this code.
nents. Like other standard Delphi components, the
2 Declare the local variables necessary to create
components that make up a report layout have a
the report.
run-time interface. That is, they can be created and
configured using Object Pascal code. This capabil- procedure TForm1.Button1Click(Sender:
ªTObject);
ity can be used to create entire reports dynamically. var
Take these steps to create a report dynamically: lTable: TTable;
lDataSource: TDataSource;
lDataPipeline: TppBDEPipeline;
1 Create data access components. lReport: TppReport;
lLabel1: TppLabel;
2 Create the report. lLabel2: TppLabel;
lDBText1: TppDBText;
3 Create the report bands. lDBText2: TppDBText;
lSysVar: TppSystemVariable;
4 Add data-aware components.
The prefix 'l' stands for local. This coding standard
5 Add formatting components. makes local variables easily distinguishable from
component level variables (which are prefixed with
These are the same steps you would follow to cre-
an 'F') and from proper component names (such as
ate a report using the Delphi IDE and the Report-
'Report1').
Builder Report Designer. Creating the components
manually requires some additional knowledge of 3 Create data access components.
how the different parts of the report fit together.
lTable := TTable.Create(Self);
The following discussion steps you through the lTable.Name := 'tblCustomer';
lTable.DatabaseName := 'DBDemos';
actual code necessary to build a simple report. lTable.TableName := 'customer.db';
lDataSource := TDataSource.Create(Self);
1 Declare the necessary uses clause. lDataSource.Name := 'dsCustomer';
lDataSource.DataSet := lTable;
uses lDataPipeline := TppBDEPipeline.Create.
DB, {contains TDataSource}
ª(Self);
lDataPipeline.Name := 'plCustomer';
DBTables, {contains TTable}
lDataPipeline.DataSource := lDataSource;
ppReport, {contains TppReport}
ppDBBDE, {contains TppBDEPipeline}
ppBands, {contains all band classes} These are standard Delphi data access components.
ppCtrls, {contains standard components}
ppTypes, {contains all ReportBuilder It is not necessary to assign the Name property of
enumerated types} these components; we've done this to give you an
ppVar; {contains SystemVariable and
Variable classes} idea of how they would be named if they were cre-
ated within the Delphi IDE.
Creating Reports in Code
84 REPORTBUILDER FUNDAMENTALS - CODE
This method creates a header band, a detail band, These components are positioned in the detail band
and a footer band. It is also possible to create the directly below their corresponding label compo-
bands individually and assign them to the report. nents.
A report must always have a detail band in order to
8 Add a page number and timestamp to the footer
generate properly.
band.
6 Add labels to the header band. lSysVar := TppSystemVariable.Create
ª(Self);
lLabel1 := TppLabel.Create(Self); lSysVar.Band := lReport.FooterBand;
lLabel1.Band := lReport.HeaderBand; lSysVar.VarType := vtPrintDateTime;
lLabel1.spLeft := 2; lSysVar.spLeft := 2;
lLabel1.spTop := 2; lSysVar.spTop := 2;
lLabel1.Caption := 'Customer No.'; lSysVar := TppSystemVariable.Create.
lLabel2 := TppLabel.Create(Self); ª(Self);
lLabel2.Band := lReport.HeaderBand; lSysVar.Band := lReport.FooterBand;
lLabel2.spLeft := lLabel1.spLeft + lSysVar.VarType := vtPageNoDesc;
lLabel1.spWidth + 3; lSysVar.Alignment := taRightJustify;
lLabel2.spTop := 2; lSysVar.spLeft :=
lLabel2.Caption := 'Company Name'; ª(lReport.PrinterSetup.PageDef.spPrintableWidth
ª -lSysVar.spWidth) -2; lSysVar.spTop := 2;
These two labels will print at the top of each page.
The 'sp' in the spLeft and spTop properties refers to Notice how the second system variable component
screen pixels. All positional properties of the com- is right-justified. The AutoSize property defaults
ponents within a report are expressed in the units of to True for system variables, so we need only to set
the report itself (i.e. the value of the Report.Units the Alignment property and component position.
property). Using the screen pixel version of these Here we set spLeft so that the component is flush
properties allows us to size and position compo- with the right margin of the page (less 2 pixels for
nents without concern for the current value of the spacing). Because it is right-justified, this compo-
Unit property. nent will expand to the right when it prints. The
PrinterSetup.PageDef object contains all of the
dimensions of the page. The spPrintableWidth
property contains the width of the paper less the
left and right margins (in screen pixels).
Creating Reports in Code
REPORTBUILDER FUNDAMENTALS - CODE 85
9 Preview the report.
lReport.Print;
DESIGN
Dialogs
Print Dialog
1 The print job settings can be set via the standard 2 Dialog with the print to file options.
dialog.
Dialogs
92 REPORTBUILDER FUNDAMENTALS - DESIGN
Print Dialog
Data Dialog
The Data dialog can be accessed from the Report |
Data menu option of the Report Designer. It can
be used to specify the data pipeline for the report.
Toolbars
REPORTBUILDER FUNDAMENTALS - DESIGN 95
Toolbars
Standard Component Palette Access the Calculations dialog (via the speed
To access this toolbar, select the View | Toolbars | menu) or the Calc tab of the Report Designer to
Standard Components menu option from the code a RAP calculation for this component.
Report Designer main menu. This toolbar will
Image
assist in creating the most commonly used report
Displays bitmaps and windows metafiles in
components.
reports. Assign the Picture property of this compo-
nent in order to place an image in your report. Use
the Report Designer's built-in picture dialog to load
images at design-time.
Label
Line
Displays text. Assign the Caption property to con-
Displays single and double lines (either vertical or
trol the text value. You can have the label resize
horizontal.) Set the Style property to control
automatically to fit a changing caption if you set
whether the line is single or double. Set the Weight
the AutoSize property to True.
property to control the line thickness in points. Set
Memo the Position property to control whether the line is
Prints multiple lines of plain text in a report. To set vertical or horizontal.
the value, assign a string list to the Lines property.
Shape
To dynamically resize the memo during printing,
Prints various shapes (squares, rectangles, circles,
set the Stretch property to True. Use the ShiftRela-
ellipses). Set the Shape property to select a type of
tiveTo property to define dynamic relationships
shape. Use the Brush and Pen properties to control
with other stretchable objects.
the color and border respectively.
RichText
TeeChart
Prints formatted text. To set the value, assign the
Displays standard (non-data-aware) TeeCharts.
RichText property or use the LoadFromFile
This component enables you to use TeeCharts
orLoadFromRTFStream methods. Use the
inside the Report Designer. You can access the
ShiftRelativeTo property to define dynamic rela-
TeeChart editor via a popup menu.
tionships with other stretchable objects. At design-
time you can use the ReportBuilder's built-in RTF BarCode
Editor to load, modify, and save rich text data Renders barcodes. The string value assigned to the
stored in files. Data property is encoded based on the BarCode-
Type. If the data to be encoded is in a database,
SystemVariable
use DBBarCode. The following symbologies are
Displays common report information such as page
supported: Codabar, Code 128, Code 39, EAN-13,
number, page count, print date and time, date, and
EAN-8, FIM A,B,C, Interleaved 2 of 5, PostNet,
time. The type of information displayed is con-
UPC-A, UPC-E.
trolled by the VarType property. The format is
controlled by the DisplayFormat property. CheckBox
Displays a checkbox using the WingDings font.
Variable
Used for calculations via an Object Pascal event
handler assigned to the OnCalc event or a RAP
event handler assigned to the OnCalc event.
Toolbars
REPORTBUILDER FUNDAMENTALS - DESIGN 97
Data Component Palette DBImage
To access this toolbar, select the View | Toolbars | Prints bitmaps or windows metafiles, which are
Data Components menu option from the Report stored in a database BLOB field.
Designer main menu. This toolbar will assist in
DBBarCode
creating data-aware report components.
Renders barcodes based on the BarCodeType and
the value supplied via the DataField property. The
following symbologies are supported: Codabar,
Code 128, Code 39, EAN-13, EAN-8, FIM A,B,C,
DBText Interleaved 2 of 5, PostNet, UPC-A, UPC-E.
Displays values from all types of database fields.
DBTeeChart
Use the DisplayFormat property to format the
Allows data-aware TeeCharts to be placed within a
value.
report.
DBMemo
DBCheckBox
Prints plain text from a memo field of a database
Displays a checkbox based on the value of the field
table. This control will automatically word-wrap
specified in the DataField property. This compo-
the text. Set the Stretch property to True and the
nent can be used with a Boolean field (or any other
component will dynamically resize to print all of
type of field via the BooleanTrue, BooleanFalse
the text. Use the ShiftRelativeTo property to
properties).
define dynamic relationships with other stretchable
objects.
DBRichText
Prints formatted text from a memo or BLOB field
of a database table. This control will automatically
word-wrap the text. Set the Stretch property to
True and the component will dynamically resize to
print all of the text. Use the ShiftRelativeTo prop-
erty to define dynamic relationships with other
stretchable objects.
DBCalc
Used for simple database calculations (Sum, Min,
Max, Count, and Average). The value can be reset
when a group breaks using the ResetGroup prop-
erty.
Toolbars
98 REPORTBUILDER FUNDAMENTALS - DESIGN
Region
Logically groups components together. Use the New Report
ShiftRelativeTo property to move the region in Creates a blank report layout.
relation to another dynamically resizing compo-
Open Report
nent (such as Memo, RichText or child-type Sub-
Displays the Open dialog, allowing you to open an
Report).
existing report layout.
SubReport
Save Report
Handles multiple master details, creates side-by-
Saves a report layout to file.
side reporting effects, and hooks reports together
as one. If you need a report to print within the con- Page Setup
text of a band, use a child-type subreport. If you Displays the Page Setup dialog, allowing you to set
need to hook reports together, use a section type the paper size and configure the layout for the
subreport. The PrintBehavior property determines report.
the subreport type.
Print
CrossTab Displays the Print dialog before sending the report
Allows you to generate a set of calculations that to the printer.
summarizes the data from a database table. It dis- Print Preview
plays the calculations in a grid format. Displays the Print Preview window.
Cut
Cuts the currently selected components into the
clipboard.
Copy
Copies the currently selected components into the
clipboard.
Paste
Pastes the components in the clipboard into the
report.
Toolbars
REPORTBUILDER FUNDAMENTALS - DESIGN 99
Edit Toolbar 4 Shape component selected
To access this toolbar, select the View | Toolbars |
Edit menu option from the Report Designer main
menu. This toolbar will assist in setting the most
important property or properties for the currently
selected component.
1 No component selected
Here a shape component has been selected in the
Report Designer. The Edit toolbar displays the dif-
ferent shape types.
Underline
Sets font to underline.
Left Justify
Left justifies the text in the component.
101
Toolbars
REPORTBUILDER FUNDAMENTALS - DESIGN
Grow Height
Determines the maximum height of all the selected
components, and then sets the height of the com-
ponents to that value.
103
Toolbars
REPORTBUILDER FUNDAMENTALS - DESIGN
Draw Toolbar
To access this toolbar, select the View | Toolbars |
Draw menu option from the Report Designer main
menu. This toolbar will assist in setting the colors
and borders of components.
Fill Color
For shapes, lines, and region components only.
Sets the Brush.Color property. To set the color of a
textual component, check the Highlight Color
action of the Format toolbar.
Line Color
For shapes, lines, and region components only.
Sets the Pen.Color property.
Line Thickness
For use with a Line component only. Sets the
Weight property.
Line Style
For use with a Line component only. Sets the
Pen.Style property.
105
Drag and Drop Support
REPORTBUILDER FUNDAMENTALS - DESIGN
Overview view, all of the fields for the currently selected data
ReportBuilder contains a Report Wizard that pipeline are displayed. Fields can be selected from
allows you to quickly create an entire report layout. the bottom list view and dragged to any part of the
This is great for generating an entire report, but report layout. The data-aware component that is
what if you need to create only a portion of a com- appropriate for the given field will then be created
plex report? Drag and drop functionality is an along with a label and border.
ideal solution for this problem because it allows
The second tab of the Data Tree is entitled Layout.
you to create a set of components within the con-
This tab allows you to control drag-and-drop
text of an existing report layout. In ReportBuilder,
behavior. A label and border are created for each
drag and drop support is provided via the Data
data-aware component by default. You can turn
Tree.
the label and the border off, control the color of the
The Data Tree has two tabs. In the top tree view, label or border, and control the font of the label and
the Data tab contains a list of data pipelines to data-aware component from this tab. Once you've
which the report has access. In the bottom list set the drag-and-drop behavior, it will be retained
for future design sessions.
5 Select Design or Preview and Finish. Report as it appears in the design workspace.
Introduction 115
Previewing 117
Custom Printer Settings 119
Report Archiving 121
Print to ASCII Text File 123
Report Emulation Text File 125
RTF, HTML, and Other Formats 127
115
Introduction
REPORTBUILDER FUNDAMENTALS - PRINT
Introduction
2 Print to Printer
The native report output in ReportBuilder takes the Several device classes are delivered standard with
form of page objects. Page objects contain draw ReportBuilder. Each device class supports a dif-
commands, which describe what the page contains. ferent physical device or file format, but the pur-
Page objects are sent to devices, which then con- pose of the device remains the same: to convert the
vert them to a format appropriate for the device. native report output of ReportBuilder to the format
The following diagram shows page objects that are appropriate for the given device. The remainder of
sent to the ScreenDevice and then converted to a this section describes the different devices and
bitmap for display in the Print Preview form. their capabilities.
page
draw command1
draw command 3
Hi there.
This is line 1.
This is line 2.
3/22/00 Page 1 of 1
117
Previewing
REPORTBUILDER FUNDAMENTALS - PRINT
Previewing
Overview Orientation
ReportBuilder contains a variety of properties that Either landscape or portrait.
allow you to control various aspects of the print
PaperHeight & PaperWidth
job. The following properties are contained in the
The dimensions of the selected paper, based on the
PrinterSetup property of the Report object and can
value of the PaperName property. If these values
be configured via the Object Inspector or the File |
are entered manually and no corresponding paper
Page Setup dialog of the Report Designer.
size is found, the PaperName is set to 'Custom'.
BinName
PaperName
The name of the bin (paper tray) containing the
The name of the paper type, such as 'Letter', or
paper on which the report will be printed. A com-
'A4'.
mon use of this property is to set it to Manual Feed
on mailing label reports. This way, you can pro- PrinterName
vide a means to load the special label paper without The name of the printer to which the report should
manually setting the printer. be printed. This property defaults to 'Default',
which will cause ReportBuilder to use the default
Collation
printer declared on your system.
When printing multiple copies of a report, this
property determines whether each copy prints as a Because all ReportBuilder reports contain a Print-
separate set of pages. erSetup object, it is possible to use section-type
subreports to achieve some fairly incredible levels
Copies
of customization of the print behavior. For exam-
The number of copies of the report that should be
ple, different pages of a report can print from dif-
printed.
ferent bins of the same printer or print to different
DocumentName printers entirely. Some of these features are show-
The name of the print job to be used when the cased in the printer setting examples provided with
report is printed - this is the name as it will appear ReportBuilder (examples 121-124).
in the Print Manager.
Duplex
For printers that support duplex, this setting deter-
mines the type of duplex printing that will occur.
Margins
The margin properties determine the left, top, right,
and bottom margins of the report.
121
Report Archiving
REPORTBUILDER FUNDAMENTALS - PRINT
Report Archiving
Overview This dialog allows you to set the default file name,
The TextFile device in ReportBuilder converts select the file format, and specify the textual com-
report output into an ASCII text file. The intent of ponents that will be saved to the file and the order
this device is to create structured data that can be that they will be saved. When utilizing the Text-
imported into another application, such as a File device, it is mandatory that these settings are
spreadsheet. The following text file formats are completed. If no components have been selected,
supported: then a blank text file will result.
Overview
By utilizing the highly extensible device architec-
ture of ReportBuilder, you can create your own
device class descendants for converting the native
output of ReportBuilder into any file format. Some
developers have already done just that, and are
offering device classes for some of the most popu-
lar file formats. These additional devices integrate
seamlessly into ReportBuilder.
TExtraDevices
by James Waler
Provides file device support for RTF, HTML,
Excel, Lotus, and Quattro Pro. A Demo is avail-
able for download. Contact James Waler directly at
www.waler.com for more details.
PsRBExportDevices
by Pragnaan Software
DEPLOY
Introduction 131
Report Templates 133
As an EXE 135
As Packages 137
International Language Support 139
131
Introduction
REPORTBUILDER FUNDAMENTALS - DEPLOY
DEPLOY
Introduction
These two approaches for deploying your applica- This strategy is similar to option 1, but the report
tion are discussed later in this section. forms are compiled into a package rather than an
executable. The advantage of this approach is that
it optimizes the size of the executable and dynami-
cally loads the package containing the reports as
needed.
Introduction
132 REPORTBUILDER FUNDAMENTALS - DEPLOY
Report Templates
As an EXE
Overview 2 Delphi 3
ReportBuilder can be deployed as part of your exe-
In order to access your Library Path in Delphi 3,
cutable. Simply include the correct path to the
select Tools | Environment Options from the Del-
compiled units (dcu files) of ReportBuilder in your
phi main menu. The Environment Options dialog
Delphi Library Path. For example:
will be displayed. Click the Library tab. The
'c:\program files\borland\delphi5\rbuilder\lib' Library Path is displayed in a drop-down combo-
box near the bottom of this dialog. It is a good idea
The 'lib' directory contains the compiled units of
to scroll through this edit box character- by-charac-
ReportBuilder. When you compile your applica-
ter using the arrow keys when checking your
tion, necessary dcu files from this directory will be
library path, as highlighting the text in this edit box
linked into the resulting executable file. Execut-
causes the cursor to jump to the end. This can
able files created this way are stand-alone in that
cause you to miss duplicate or incorrect directories
they can be distributed successfully without any
in the path.
supporting files.
As Packages
Overview
You can optimize the size of your executable by
compiling your project with packages. To compile
with packages, access the Project Options dialog,
select the 'Packages' tab, and click on the 'Build
with Packages' check box. The list of package
names that appears to the left of this check box
should include the following ReportBuilder run-
time packages:
Overview
ReportBuilder includes support for 12 built-in lan-
guages. The strings for each language reside in
separate resource files. These files are located in
the ..RBuilder\Languages directory, under a subdi-
rectory named for the given language. Three letter
codes are used to differentiate between the lanuage
DLLs, which are installed in the Windows/System
directory.
Languages
Only the languages that are explicitly selected dur- The language DLLs that appear in Windows\Sys-
ing install will appear in the Languages folder. The tem are listed below:
'cst' folder will always appear in the Languages
File Name Description
folder because it represents the custom language
rbPrint.dft Strings used by ReportBuilder
type. The cst folder contains the resource files that
correlate to the lgCustom enumerated type. The rbIDE.dft Strings used by the Report
custom language can be modified to contain your Designer
own translation, which will then appear in the
The resource files that appear in RBuilder\Lib are
ReportBuilder user-interface when the Report.Lan-
listed below:
guage property is set to lgCustom.
File Name Description
The Default Language rbPrint.res Strings used by ReportBuilder
When ReportBuilder is installed, the installation
program allows you to specify a default language rbIDE.res Strings used by the Report
and any additional languages you wish to use. The Designer
installation will then install the appropriate files You can change the default language used by
onto your system. The Report.Language property ReportBuilder by copying the appropriate language
defaults to the lgDefault language type. This type files from the RBuilder\Languages directory to the
correlates to the language resource files located in RBuilder\Lib and Windows\System directories
the RBuilder\Lib directory and the language DLLs respectively. For the DLL files, make sure that you
located in the Windows\System directory (the change the extension to .dft. The following copy
DLLs with the .dft extension). The .res files are commands will change the default language to
used when compiling stand-alone executables in Swedish when issued at the MS-DOS prompt
Delphi. The DLLs are used to provide language (from within the RBuilder\Languages\sve direc-
support at Delphi design-time. When Report- tory):
Builder installs, it copies these files to the appro-
copy rbPrint.res
priate directories. c:\progra~1\borland\delphi5\rbuilder\lib
ªcopy rbIDE.res
c:\progra~1\borland\delphi5\rbuilder\lib
ªcopy rbPrint.sve
c:\windows\system\rbPrint.dft
ªcopy rbIDE.sve
c:\windows\system\rbIDE.dft
Main 147
Data 167
Code 191
Design 217
Print 221
Deploy 225
MAIN
Introduction 147
The Delphi Components 151
Designer Component 153
Report Explorer 157
Data Dictionary 159
Putting It All Together 161
On-Line Help 163
147
Introduction
REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - MAIN
Introduction
Data
Within the work environment of the Data tab, end
users can quickly create dataviews, which can then
be used to supply data to reports. Dataviews are
usually created via the Query Wizard or Query
Designer. Both of these tools are visual; they also
In ReportBuilder Enterprise, the goal is to deliver a allow the end user to select the tables, fields, search
full-fledged reporting solution to end users. This criteria, and sort order necessary for the report.
goal is achieved by delivering visual, easy-to-use Behind the scenes, an SQL statement is generated
solutions in each of these four areas. This screen and used to retrieve the data from the database. A
shot of the ReportBuilder Enterprise Report screen shot of a completed dataview is shown
Designer shows the ergonomic design of the user- below.
interface.
Introduction
148 REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - MAIN
Design Preview
The Design workspace contains the actual layout The Preview workspace contains the rendered
of the report. The user-interface is identical to the report. The report can be printed to the printer or
one presented to developers using ReportBuilder at to various file formats from this workspace.
Delphi design-time; in other words, it is full-fea-
tured and professional. The Office97-style inter-
face makes the Design workspace especially easy
to learn for end users. A Report Wizard is avail-
able for creating reports quickly. You can custom-
ize this interface by replacing any of the dialogs it
uses and by registering your own report wizards.
151
The Delphi Components
REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - MAIN
Delphi Components
ArchiveReader
After you print a report to an archive file (.raf
extension), you can read and preview the file via
this component. Just assign the ArchiveFileName
to the file and call the Print method. In terms of
displaying a report, this component works the same
as the Report component.
DataDictionary
Used by the QueryWizard component to convert
raw table and field names into more usable aliases.
This component is generally used only when you
are creating an end-user reporting solution.
Designer
Used when you want to deploy the Report
Designer to your end users. See the End-User
demo (Demos\EndUser directory).
ReportExplorer
Used to provide a Windows Explorer-style inter-
face to End-User Reporting solutions developed
using ReportBuilder Enterprise. See the End-User
demo (Demos\EndUser\1 Report Explorer\ direc-
tory).
153
Designer Component
REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - MAIN
Designer Component
Overview Report
The Designer is a non-visual component that acts The report object that will be used to load and save
as a 'wrapper' around the Report Designer window reports. The configuration of the Report Template
displayed in the end-user reporting solution. By properties is used by the Report Designer to deter-
setting the various properties and events of the mine how reports will be loaded and saved.
designer component, you customize the content
ShowComponents
and behavior of the Report Designer. The most
Determines which components will be displayed in
commonly used properties are listed below.
the ReportBuilder component palettes. Sometimes
AllowDataSettingsChange used to disable advanced components such as
Used to control whether the DataSettings menu regions or subreports.
option appears in the File menu of the data work-
TabsVisible
space. Usually disabled to prevent end users from
Determines whether the Design and Preview tabs
changing the database settings.
will display. When set to false, the Report
AllowSaveToFile Designer becomes a 'design only' window, where
When set to True, the File menu of the design the end user can work on the layout, but cannot
workspace has 'Load from File' and 'Save to File' preview. If DADE or RAP is installed, then this
menu options. property cannot be set to False.
DataSettings
DADE only. Used to configure DADE (data work-
space) for a given database.
Icon
The icon to be displayed on the Report Designer
window.
RAPInterface
RAP Only. RAP configuration settings.
RAPOptions
RAP Only. Further RAP configuration settings.
Designer Component
154 REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - MAIN
A Simple End-User Report Solution 4 Code the OnClick event of the button to launch
We can create a simple end-user reporting solution the designer.
using just a designer component and a report com-
ponent.
Report Explorer
ModalForm
Whether or not the report explorer form should be
displayed modally. Defaults to True.
Report Explorer
158 REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - MAIN
Data Dictionary
table field
TableName C(60) TableName C(60)
TableAlias C(60) FieldName C(60)
FieldAlias C(60)
TppBDEPipeline: plTable TppBDEPipeline: plField
Selectable C(1)
Searchable C(1)
Sortable C(1)
DataType C(60)
AutoSearch C(1)
Mandatory C(1)
TppDataDictionary
TppDesigner
161
Putting It All Together
REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - MAIN
Summary
In order to create the most sophisticated and com-
plete end-user reporting solution possible, we need
to connect and configure all of the components
available in ReportBuilder Enterprise. The screen-
shot below shows the configuration of a full-fea-
tured end-user reporting solution (the colored
shapes and labels have been added for informa-
tional purposes only). A completed version of this
solution is available in the
\RBuilder \Demos\EndUser\1. Report Explorer
directory. Step-by-step instructions for creating
this application are provided in the 'Building an
End-User Reporting Application' tutorial.
163
On-Line Help
REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - MAIN
On-Line Help
Overview
The ReportBuilder On-Line Help contains over
1,500 topics documenting the properties, events,
and methods of the various components that make
up the product.
DATA
Introduction 167
Query Wizard 169
Query Designer 173
Configuring DADE 181
DADE Architecture 183
Extending DADE 185
167
Introduction
REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - DATA
DATA
Introduction
Query Wizard
Overview 2 Select the first table for the query. The cus-
Within the data workspace, you can select data tomer table has been selected.
from your database using an SQL query. This
functionality is provided via query-based data-
views, which can be visually created using the
Query Wizard and visually maintained using the
Query Designer.
4 When we return to the query wizard, both tables 6 Skip the calculations page, since this query will
are shown as selected. not contain calculations.
5 Skip the fields page, since we want to select all 7 Skip the groups page, since this query will not
fields. be grouped.
171
Query Wizard
REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - DATA
8 Skip the search criteria page; all records will be 10 Name the dataview. The data pipeline name is
selected. automatically generated when we name the data-
view. The next action will be to preview the data.
Query Designer
3 Click on the field that has been added to the list 5 Click on the SQL tab to make sure the criteria
of criteria at the bottom and select the operator. value is valid.
7 Preview the data and make sure that the These types of calculations can be created on the
intended records are selected. Calc tab of the Query Designer. Perform these
steps in order to sum the amount paid for all cus-
tomers in the orders table:
3 Select 'Sum' as the function type for the calcula- 5 Click the SQL tab to make sure the generated
tion. SQL is valid.
4 Enter the Field Alias you would like to use for 6 Close the Query Designer and click the Preview
this calculated field. icon to preview the data.
177
Query Designer
REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - DATA
5 Enter the Field Alias you would like to use for 7 Close the Query Designer and click the Preview
this calculated field. icon to preview the data.
Configuring DADE
Overview UseDataDictionary
The first step in configuring DADE for your end Determines whether the data dictionary object
users involves setting the properties of the DataSet- assigned to the DataDictionary property will be
tings object of the Designer component. This used.
object contains the following properties:
Database Product and SQL Type
AllowEditSQL If you intend to use the Query Wizard and Query
Determines whether or not the end user can edit the Designer, then the SQLType is vital. The follow-
SQL in the Query Designer. ing table shows the recommended SQLType for a
given database product.
DatabaseName
The name of the database from which data will be Database Product SQLType
retrieved when the query executes. Paradox sqBDELocal
Interbase SQL2
DataDictionary
Oracle SQL1
The data dictionary object that will convert raw
MS Access SQL2
table and field names to aliases.
Sybase SQL ServerSQL1
SessionType Sybase SQL AnywhereSQL2
Defaults to BDESession. Should only be changed MS SQL ServerSQL2
if you have created your own Session class in order
to use the Query Wizard with a proprietary data-
base engine.
SQLType
Defaults to sqBDELocal. If you are not using
dBase or Paradox tables, then you should set this
property to sqSQL1, as the Local SQL dialect is
not supported by most other database types. If
your database supports ANSI-92 SQL, then you
can set this property to sqSQL2 instead of sqSQL1.
Configuring DADE
182 REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - DATA
Data Settings
Once you have configured the data settings, you
may notice that a Data Settings menu option
appears on the File menu of the data workspace
when you run your application. This option dis-
plays a dialog that allows the end user to modify
the data settings. If you do not want the end user to
be able to change these settings, then you can set
the AllowDataSettingsChange property of the
Designer component to False.
183
DADE Architecture
REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - DATA
DADE Architecture
daDataVw TdaCustomDataView
TdaDataView
Dataviews represent a set of data and are visually
daQuery
TdaBDEDataSet TdaBDESession
created and maintained in the data workspace of
the Report Designer. Internally, a dataview creates
TdaQueryDataView TdaBDETemplateDataView
the data access objects necessary to connect a
daDBBDE report to data. The interface from the dataview
TdaBDEQueryDataView TdaBDEQueryTemplateDataView
into the other workspaces of the Report Designer is
composed of the data pipelines, which are con-
daQClass
TdaSQL tained by the dataview. A dataview must have at
least one data pipeline. A typical dataview will
contain one or more data pipelines, datasources,
The inheritance relationships are indicated by tri-
and datasets.
angles in the above diagram. Where one class is
associated with another class, a line is used. If the TdaDataView contains the declarations of the
line terminates in a diamond shape, then it indi- methods that descendants must implement. It is in
cates that the class actually forms part of the inter- the ppClass unit because it declares a Report prop-
nal implementation of the component. For erty that refers to TppCustomReport. If you need
instance, the TdaSQL class is part of the imple- to know the main report with which a dataview is
mentation of the TdaQueryDataView. The unit in associated, you can always use this property.
which each class is declared is indicated by the text
at the upper left corner of each containing shape.
DADE Architecture
184 REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - DATA
Extending DADE
2 Here we can see that four different dataview 4 As you can see in the data pipeline list of this
templates have been registered. After double- dataview, this template has declared relationships
clicking on the 'Order' template, the following between the customer, order, and order items
screen would appear: tables. Each table is independent and has its own
data pipeline. By clicking on the Design tab and
accessing the Report | Data menu option, we can
see how this dataview has assigned the data pipe-
lines to the report:
3 This is a custom dialog created by the developer The customer data pipeline is assigned to the
of the Order dataview template. It allows the end report. The order and item data pipelines are avail-
user to enter simple search and sort criteria. Once able, and we could create subreports and assign
we've done this and clicked OK, the completed data- them to these data pipelines. This sort of data pipe-
view will be displayed: line configuration is not available from query-
based dataviews, which is why the developer chose
to create this dataview template.
187
Extending DADE
REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - DATA
TTable: Employee
• Dataviews are created and maintained visually in
the data workspace of the report designer.
Classes TdaADOQueryDataView
Implementing a QueryDataView descendant • Descendant of TppQueryDataView
requires us to define the following set of classes:
• Uses the above classes to create the required
TdaChildADOQuery Query DataSource Pipeline Report
• Descendant of TADOQuery that can be a child connection
of a DataView
• Uses the TdaSQL object built by the QueryWiz-
• Override the HasParent method of Tcomponent ard to assign SQL to the ADOQuery, etc.
to return True
DADE Plug-ins:
• Must be registered with the Delphi IDE via Reg- If you have Delphi Enterprise, you can see these
isterNoIcon classes in action by installing the ADO demo. The
following DADE Plug-ins are provided with
TdaChildADOTable
ReportBuilder Enterprise. Examples can be found
• Descendant of TADOTable that can be a child
in \RBuilder\Demos\EndUser Databases.
of a DataView
• ADO
• Override the HasParent method of Tcomponent
to return True • IBX
• Implements GetDatabaseNames
• GetTableNames, etc.
TdaADODataSet
• Descendant of TppDataSet
CODE
Introduction 191
The Calc Workspace 193
Writing RAP Code 201
Configuring RAP 205
Extending RAP 209
Debugging RAP Code 211
191
Introduction
REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - CODE
CODE
Introduction
Overview
RAP (Report Application Pascal) and the inte- The Report Application Programming language (or
grated development environment that can be used RAP for short) is designed to allow developers and
to create RAP programs are the result of the dis- end users to code calculations, event handlers, and
covery that a visual solution for data processing stand-alone procedures for use with ReportBuilder
and calculation was needed for end users. Even Enterprise. RAP programs can be created, modi-
though RAP consists of an object-oriented com- fied, compiled, and executed at run-time.
piler and extensible architecture 'under the covers',
About RAP
it appears as a simple, easy-to-use calc workspace
within the Report Designer. The calc workspace is
RAP is easy to learn.
pictured below. The code editor window at the
The RAP language is identical to Object Pascal. If
bottom of the workspace shows a simple event
you know how to code Delphi event handlers, you
handler assigned to a line component.
know how to code RAP; therefore, the learning
curve for Delphi developers is minimal.
Overview
The Calc workspace is the development environ- You can include the Calc workspace in your end
ment for RAP. With all of the RAP options avail- user projects by adding raIDE to the uses clause of
able, the Calc workspace is a powerful Pascal one of your units. When your users select the Calc
development environment. For most end users, this tab, they will see the RAP IDE. The RAP IDE
may be more than they need. Judging your users' consists of:
needs, you should define just how much of the
RAP IDE to make available to them. • The Code Explorer
• The Code Editor
• The Message Window
• The Code Toolbox
A Code Explorer: Contains the tree view (left) and C Message Window: Messages from the compiler
the list view (right) are presented here
B Code Editor: The space where you code and D The Code Toolbox: Contains pieces of code that
you compile the report drag into the Code Editor
The Calc Workspace
194 REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - CODE
Variables View
The Variables view of the Code Explorer is dis-
played by right-clicking the left pane and selecting
Variables from the context menu.
This view displays a listing of all components con-
tained within the report. The right pane displays
any events associated with the currently selected
component. Selecting an event will display the
event handler, if one exists.
In the treeview, you will notice small arrow shaped Module View
images to the left of some nodes. These are Compi-
lation State Indicators. They are used to tell you The Module view of the Code Explorer is dis-
where your code is and what state it is in. There are played by right-clicking the left pane and selecting
five possible indicators: Module from the context menu.
The Code Editor's context menu contains the fol- Message Window
lowing items: The Message Window functions in essentially the
same manner as Delphi's message window. Mes-
New
sages from the compiler are presented here. You
New has the same effect as clicking in the Code can navigate to the location of compiler errors by
Editor. It is only enabled if there is no implementa- double-clicking the error message.
tion for the item currently selected in the Code
The Code Toolbox
Explorer.
The Code Toolbox is a visual code repository. It
contains most of the identifiers and code elements
Compile
that the RAP compiler recognizes.
Compile activates the RAP compiler to attempt to
compile the current procedure and any procedures The Code Toolbox enables you to:
upon which the current one depends.
• View identifiers grouped by available data, visi-
Save ble object properties or language features
The Calc workspace maintains an intermediate • Generate code by dragging identifiers into the
buffer for the Code Editor. Selecting Save will Code Editor. Functions dragged into the editor
commit the current contents of the Code Editor to will generate a place-holder parameter list. For
the buffer; it will not save the entire report. Select- example, the following code is generated when
ing Save has the same effect as navigating away you drag the Copy function into the Code Editor:
from, and then returning to the current procedure.
Copy(S, Index, Count);
Delete
The Data tab of the Code Toolbox displays data The Objects tab of the Code Toolbox displays
pipelines and fields, allowing you to drag and drop report objects and their properties, allowing you to
field references into the Code Editor. drag and drop properties into the Code Editor.
Selecting a pipeline from the list will display all of Selecting an object from the tree will display a list
the fields in that pipeline as well as data type and of that object's properties.
size information for the fields. To insert a property into the Code Editor, select the
property and drag it into the Code Editor. The code
To insert a field value into the code editing win- necessary to retrieve the value of the property or
dow, select the field and drag it into the Code Edi- call the method will be generated. For example,
tor. The code necessary to retrieve the field value dragging the 'AutoSize' property from the Code
from the pipeline will be generated. For example, Toolbox pictured above would result in the follow-
dragging the 'City' field from the Code Toolbox ing code:
pictured above would result in this code:
Label1.AutoSize
Value := Clients[’City’]
199
The Calc Workspace
REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - CODE
The programs and variables declared in the global procedure Variable1OnCalc (var Value: Variant);
section of a module are visible to all subreport code begin
Result :=
end;
Writing RAP Code
204 REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - CODE
end;
Configuring RAP
End User Configurations The RAP user interface can be configured to meet
When building an end user solution, you must the needs of your end users. There are two basic
decide how much of RAP's functionality to expose configurations available:
to your users. RAP allows a continuum from a cal-
1 Calculations Dialog
culations dialog to a full development environ-
ment. Likewise, you can give your users only the For casual end users, a simple Calculations dialog
base language features included in RAP, or you can is accessible from the speedmenu of the TppVari-
expose new, custom pass-through functions, make able component. This dialog provides a place for
RAP aware of your own classes and even allow calculations to be entered and returned via a single
users to display custom forms you design. Result parameter. The calculation result is then
displayed in the variable when the report prints.
The two main properties used for scaling the RAP
environment are TppDesigner.RAPOptions and In order to configure the user interface to provide
TppDesigner.RAPInterface. this level of functionality, set the RAPInterface
riNotebookTab property to False and the riDialog
The RAPInterface property controls how the Calc
property to True. The figure below illustrates the
workspace will be presented to the user — as a dia-
Calculations... option available when the end user
log, a tab or both.
accesses the speed menu of a variable.
When RAP is presented as a Calc tab in the Report
Designer, RAPOptions allows you to specify how
much the user is able to view and edit.
Configuring RAP
206 REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - CODE
In this configuration, your users have the same This view shows the report and all of the objects
functionality as in the Calc Dialog, but it is avail- within it. The user has access to all the report
able in the Calc tab. In the Calc dialog, the Code objects' events, and can code event handlers for
Explorer is not shown since, in that dialog, we deal them. The right pane displays any events associ-
with only one variable at a time. However, in the ated with the currently selected component.
Calc tab, the explorer is shown. In order to config- Selecting an event will display the event handler, in
ure the user interface to provide this level of func- one exists. An event handler can be coded for any
tionality, set the RAPInterface riNotebookTab object. This view is good for viewing all report
property to True and set all of the RAPOptions to objects and their events.
True. When the Report Designer is displayed, the
Calc tab will be visible. If you right-click on the
treeview on the left, a speed menu that shows the
different views of calculations available will be
displayed:
A Variables
Extending RAP
The method for making the RAP compiler aware of 1 Identify a Delphi function to call. This can be a
functions is to declare descendants of TraSystem- function you have written, a DLL call, a Win API
Function – one for each function – and to register call or a standard VCL function.
them with the compiler using raRegisterFunction.
2 Create a TraSystemFunction descendant.
Each descendant class overrides ExecuteFunction
– this method tells the RAP compiler what to do 3 Return the signature of your procedure in the
when a function name is encountered in the users' GetSignature method.
code, thus passing-through the true Delphi func-
4 Indicate whether the call HasParams and
tionality to the end user.
IsFunction via these two boolean methods.
For example, when the RAP compiler comes upon
5 Make the actual call to the Delphi function or
the Copy function, it executes the ExecuteFunction
procedure in the ExecuteFunction method.
method which, in essence, tells RAP how to assign
the function's parameter list, then calls Delphi's 6 Register your new function with RAP via a call
Copy function. to raRegisterFunction. Place this call in the initial-
ization section of the unit containing the descen-
For examples of registering new pass-through
dant class.
functions, see the main RAP demo:
RBuilder\Demos\0. RAP\1. Main\RAP.dpr – 7 Add this unit to your project.
reports #31-33. Also see the Adding Functions When you run the application, you will see your
Tutorial. new function in the language tab of the Code Tool-
box. Also, you will be able to call the function
from any RAP event handlers or programs you cre-
ate. For a detailed tutorial, see Adding New Func-
tions to RAP.
Extending RAP
210 REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - CODE
Using the CodeSite Functions This is a fairly simple example, but you can see
For those unfamiliar with CodeSite, here are some that the liberal use of CodeSite calls can be essen-
ideas for how to use it with RAP. Note that this is tially like stepping through code, looking at values.
not a primer on using CodeSite; see the CodeSite
There is a demo project showing the use of the
documentation for that information.
CodeSite pass-through functions in
Let us say, for instance, that a TppVariable is not RBuilder\Demos\0. RAP\2. CodeSite.
displaying a value you think it should and you want
to make sure that a section of code is actually being
executed. You might add the following code to the
variable's OnCalc event:
csEnterMethod('Variable1OnCalc');
csSendString('TaxRate', plCustomer['TaxRate']);
if plCustomer['TaxRate'] > 8 then
begin
csSendBoolean('Detail.Overflow', Detail.Overflow);
if Detail.Overflow then
begin
lsLabelText := 'Continued...';
Value := '';
end
else
begin
lsLabelText := plCustomer['Company'];
Value := GetMyValue;
end;
csSendString('Value', Value);
end
else
begin
csSendWarning('Invalid TaxRate');
Value := 'Invalid';
end;
csExitMethod('Variable1OnCalc');
end;
213
Debugging RAP Code
REPORTBUILDER ENTERPRISE EDITION FUNDAMENTALS - CODE
Conditionally Compiling CodeSite Sup- To disable CodeSite support for your report while
port not removing the CodeSite calls themselves, do the
Repeatedly adding and removing CodeSite calls following:
can be troublesome, especially if you have many of
1 Open the raCSFuncs unit.
them riddling your code. For that reason, the Code-
Site calls can be conditionally compiled. All of the 2 Scroll to the top of the unit, just below the inter-
CodeSite functions in the raCSFuncs unit have face clause.
conditional statements around their ExecuteFunc-
3 To enable CodeSite support, add an ’x’ at the
tion implementations and at the beginning of the
beginning of the line between the '{' and the '$'.
unit is the line:
{$DEFINE CODESITE}
{x$DEFINE CODESITE}
4 Add an 'x'
In order to enable the function implementations,
remove the "x" from the beginning of the line. To 5 Save the unit.
disable them, add the "x". This will allow you to 6 Rebuild your project by selecting Build All in
leave all of the CodeSite calls in the code without Delphi.
activating the CodeSite object on your user's
machine.
DESIGN
DESIGN
New Report
Creates a new report and displays the Report
Designer.
Open Report
Opens the currently selected report and displays it
in the designer.
Print
Prints the currently selected report.
Print Preview
Opens the currently selected report and displays it
in the print preview window.
.
REPORTBUILDER ENTERPRISE FUNDAMENTALS - PRINT
End-User Options
DEPLOY
Summary 225
225
Summary
REPORTBUILDER ENTERPRISE FUNDAMENTALS - DEPLOY
DEPLOY
Summary
Allow the report component to reside in an invisi- A full-featured implementation of Option A above
ble form along with the necessary data access is provided in the 'Building a Reporting Applica-
objects. When it is time to print the report, instan- tion' tutorial in the Developer's Guide. Option A
tiate the form and call the Print method. You could has the advantage of requiring the least code. The
slightly vary this architecture by using a data mod- main advantage of options C and D is that you can
ule as a container for the data access objects. This change report layouts and redeploy them to your
method requires the form to contain the ppReport end users with regenerating your executable.
component. Because Option A compiles the report layouts into
the executable, it requires a recompile any time a
B Compile reports into a package.
report must be changed. In terms of report layout
Similar to option A, but rather than compile the load time or print speed, all options are essentially
forms containing the reports into the executable, equal.
the report forms are compiled into a package. The
advantage of this approach is that it optimizes the
size of the executable and dynamically loads the
package containing the reports as needed.
REPORT TUTORIALS
REPORT TUTORIALS
Creating a Report Via the Data Tree
7 Save the project under the name rbDTProj in the Create a Report and Connect it to the
My RB Tutorials directory. Data
Note: Save your work frequently to avoid losing 1 Add a Report component to the form.
changes should your computer unexpectedly lose
2 Configure the Report component:
power or crash.
DataPipeline plCustomer
Create a Table, DataSource, and
Name rbCustomerList
DataPipeline Component
1 Select the Data Access tab of the Delphi compo- Invoke the Report Designer and Set the
nent palette. Paper Orientation
1 Double-click on the Report component to dis-
2 Add a Table component to the form.
play the Report Designer.
3 Configure the Table component:
2 Size and move the Report Designer window so
DatabaseName DBDEMOS that the Object Inspector is visible.
Name tblCustomer
3 Select the File | Page Setup option from the
TableName customer.db
Report Designer main menu.
4 Add a DataSource component to the form.
4 Click the Paper Size tab and change the paper
5 Configure the DataSource component: orientation from Portrait to Landscape, then click
DataSet tblCustomer the OK button.
Name dsCustomer Set the Header Band Height to 1 inch
6 Select the RBuilder tab of the Delphi compo- 1 Place the mouse over the gray divider entitled '^
nent palette. Header'. The cursor should change to a double-
sided arrow. Hold down the left mouse button,
7 Add a DBPipeline component to the form. drag down a short distance, and release the mouse
button. Check the vertical ruler on the left and
8 Configure the DBPipeline component: drag down until you can see the 2 inch mark.
DataSource dsCustomer 2 Drag the band divider up until the top guide
Name plCustomer indicates you have reached the 1 inch mark.
3 Right-click over the white space of the header 7 Place another label near the center of the header
band and access the Position dialog. The value for band.
the height should be 1.
8 Configure the label:
Create Labels in the Header Band
Caption Marine Adventures &
1 Click the Label component icon on the Sunken Treasure Co.
Report Designer component palette.
Font Name Times New Roman
2 Click on the left side of the header band. A Font Size 16
label will be created in the header band. It will Font Style Bold & Italic
become the current selection in the Object Inspec- Text Alignment Centered
tor.
9 Set the font color to maroon by clicking on the
3 Locate the Edit box at the upper left corner of
right side of the Font Color icon to display the
the Report Designer. Select the text inside it and
drop-down Color Palette, then clicking on the
type Customer List.
maroon colored square.
4 Locate the font controls on the Format bar.
Note: When you select a color via the Font or
Note: The font controls appear to the right of the Highlight Color icons, the selected color is dis-
Edit box and provide the following functions: played below the icon. You can then click on the
icon directly (without re-displaying the drop-down
• Font Name drop-down list
color palette) and the currently selected component
• Font Size drop-down list
or components will be set to that color.
• Bold
• Italic 10 Position the Marine Adventures label at the top
• Underline Font Style of the header band workspace area.
• Text Alignment
11 Select View | Toolbars | Align or Space from the
• Font Color
Report Designer main menu. The toolbar should
• Highlight Color
appear as a floating window.
5 Set the font:
12 Click and drag the toolbar window to the left
Font Name Times New Roman side of the Report Designer and position it so that it
Font Size 12 docks to the left of the vertical ruler.
Font Style Bold & Italic
13 Center the label by clicking the Center Horizon-
6 Position the label at the upper left corner of the tally icon on the Align or Space toolbar.
header band.
layout check
Creating a Report Via the Data Tree
232 REPORT TUTORIALS
Use the Data Tree to Lay Out the 4 Click on the CustNo field and then hold down
Customer Information the Ctrl key and click on the following fields in the
1 Select View | Toolbars | Data Tree. Position the order specified:
Data Tree to the left of the Report Designer.
Company
2 Click the Layout tab at the bottom of the Data Contact
Tree and configure the drag-and-drop settings as Phone
follows: FAX
6 Close the Data Tree window. Note: If you cannot select all objects because you
need to scroll to the right, then select as many as
you can and release the mouse button. Now scroll
layout check
11 Make sure it is set to psTwoPass. This property Preview the Report at Run-time
is set automatically when you select a SystemVari- 1 Close the Report Designer window.
able type that requires a Page Count.
2 Select the Standard tab of the Delphi component
Note: Setting the report PassSetting on psTwoPass palette.
will cause the report engine to generate all of the
3 Add a Button component to the form.
pages automatically. One-pass reports only gener-
ate the first page, and then any pages requested 4 Configure the Button component:
after that. This does not allow the report to calcu-
Name btnPreview
late the total number of pages. Two-pass reports
Caption Preview
are required whenever you are using the Page-
Count in a System Variable. 5 Add the following code to the OnClick event
handler of the button:
12 Select File | Save from the Delphi main menu.
rbCustomerList.Print;
13 Click the Preview tab in the Report Designer.
6 Select File | Save from the Delphi main menu.
• Use the Report Wizard to create report layouts 3 Select File | Save As from the Delphi menu and
save the form under the name rbViaWiz in the My
• Save and load report layouts to report
RB Tutorials directory (established on page 181).
• template files (.rtm)
Note: It is important to name the form and save the
• Add code to preview and print the report at run- form's unit using the names given above because
time the report will be used in later tutorials.
Tabular Report 4 Select View | Project Manager from the Delphi
main menu.
Create a Table, DataSource, and Invoke the Report Designer and Access
DataPipeline Component the Report Wizard
1 Select the Data Access tab of the Delphi compo- 1 Double-click on the Report component to dis-
nent palette. play the Report Designer.
2 Add a Table component to the form. 2 Select File | New from the Report Designer's
menu.
3 Configure the Table component:
3 Double-click the Report Wizard icon (or click
DatabaseName DBDEMOS
the OK button while the icon is selected).
Name tblCustomer
TableName customer.db Use the Report Wizard to Lay Out a
IndexFieldName Company Tabular Style Report
1 Click on the Data Pipeline Name drop-down list
4 Add a DataSource component to the form.
and select the Customer table.
5 Configure the DataSource component:
2 Click on the Company field in the Available
DataSet tblCustomer Fields list box and click the arrow button ‘>‘ to
Name dsCustomer move the field to the Selected Fields list box.
6 Select the RBuilder tab of the Delphi compo- Note: You can also move a field to the Select
nent palette. fields list box by double-clicking it.
7 Add a DBPipeline component to the form. 3 Repeat this procedure to select the following
fields:
8 Configure the DBPipeline component:
CustNo
DataSourcedsCustomer Contact
NameplCustomer Phone
FAX
Create a Report and Connect it to the City
Data State
1 Add a Report component to the form. Country
DataPipeline plCustomer
Name rbCustomerList
239
Creating a Report Via the Report Wizard
REPORT TUTORIALS
4 Click the Next button to access the next page of Preview the Report
the Wizard. 1 Click the Preview tab.
5 This page of the Report Wizard is used to define 2 Click the Page Width and 100% buttons to view
groups. No groups are required for this example; the report on a larger scale.
therefore, click the Next button again.
3 Type 80 in the % edit box and press enter.
6 Click the Landscape radio button located in the
4 Type 120 in the edit box and press enter again.
Orientation group box.
The report can be scaled for viewing at any size up
7 Click the Next button. to 250%.
8 Click on each of the style options in the list box 5 Click the Page Width button to continue view-
to preview each of the available styles. ing the report.
9 Select the Corporate style and click the Next 6 Click the Next and Prior page buttons to navi-
button. gate through the pages of the report.
10 Click the Finish button. The report layout will 7 Click the Print button to access the print dialog.
be generated and the Preview tab of the Report From here you can print All, Current, or a specified
Designer will be selected so that you can view the Range of pages. Click the Cancel button to close
report. the dialog.
12 Select the CustNo label and DBText compo- Set the Report to Two-Pass Mode
nents and click the Left Justify icon. 1 Select the System Variable component on the far
right of the footer band.
layout check
5 Make sure it is set to psTwoPass. This property Use the Report Wizard to Lay Out a Ver-
is set automatically when you select a SystemVari- tical Style Report
able type that requires a Page Count. 1 Select File | New from the Report Designer's
menu.
Note: Setting the report PassSetting on psTwoPass
will cause the report engine to generate all of the 2 Double-click the ReportWizard icon (or click
pages automatically. One-pass reports only gener- the OK button while the icon is selected).
ate the first page, and then any pages requested
3 Click on the Data Pipeline Name combo box
after that. This does not allow the report to calcu-
and select the Customer table.
late the total number of pages. Two-pass reports
are required whenever you are using the Page- 4 Click on the Company row of the Available
Count in a System Variable. Fields list box and click the arrow button '>' to
move the field to the Selected Fields list box.
Save the Report Layout to a Template
File 5 Repeat this procedure to select the following
1 Select File | Save As from the Report Designer's fields:
menu.
CustNo
2 Type CustTab in the File Name edit box and Contact
click the Save button. Be sure to save the template Phone
in the same directory as your project. FAX
City
Note: By default, the report layout will be saved
State
with the form on which the TppReport component
Country
resides. Saving the layout of a report to a template
file is optional. However, for this example we 6 Click the Next button to access the next page of
want to create two report layouts for the same data. the Wizard.
The user can choose which layout to print at run-
7 This page of the Report Wizard is used to define
time. Therefore, we will save the report layouts to
groups. For this example no groups are required;
.rtm files and load the appropriate layout at run-
therefore, click the Next button again.
time.
8 Click the Vertical radio button located in the
Layout group box.
11 Click the Finish button. The report layout will 5 Right-click over the line component at the top of
be generated and the Preview tab of the Report the detail band and set the ParentWidth property to
Designer will be selected so that you can view the True.
report layout.
Note: When using the Component popup menus, a
12 Click the Design tab. checkmark next to a menu option indicates the
property is set to True. Selecting the menu option
13 Select the CustNo label and DBText compo-
toggles the property from Checked to Unchecked
nents and click the Left Justify icon.
(i.e. True to False) and vice-versa.
14 Select the System Variable component on far
6 Preview the report again. You should see two
right of the footer band.
columns.
15 Use the drop-down list control in the far left cor-
Note: Quite often, you will want to use the Report
ner of the Report Designer to change the variable
Wizard to layout a report and then customize the
type from PageNoDesc to PageSetDesc.
report layout further using the Report Designer.
Name gbReportStyle
Caption Report Style
Left 15
Top 11
Width 131
Height 82
Name rbTabular
Caption Tabular
Checked True
Left 18
Top 23
Width 65
Name rbVertical
Caption Vertical
Left 18
Top 50
Width 65
4 Add event handlers for each Radio Button's 5 Click the Preview button to view the tabular
OnClick event as shown below. style report.
5 Add ppTypes to the uses clause of your form's 6 Click the Vertical radio button.
unit.
7 Click the Preview button to view the vertical
Note: The ppTypes unit contains the declaration style report.
for all enumerated types and constants used in
Note: You can also send the report to the printer by
ReportBuilder. In this instance, it is needed to sup-
clicking the Print button.
port the references to dtPrinter and dtScreen in the
preceding button click event handlers.
Vertical Report
247
A Simple Report the Hard Way
REPORT TUTORIALS
• Work with the Report Designer 3 Select File | Save As from the Delphi menu and
save the form under the name rbCust in the My RB
• Create and configure the most common report
Tutorials directory (established on page 181).
components
Note: It is important to name the form and save the
form's unit using the names given above because
the report will be used in later tutorials.
Create a Table, DataSource, and Invoke the Report Designer and Set the
DataPipeline Component Paper Orientation
1 Select the BDE tab of the Delphi component 1 Double-click on the Report component to dis-
palette. play the Report Designer.
2 Add a Table component to the form. 2 Size and move the Report Designer window so
that the Object Inspector is visible.
3 Configure the Table component:
3 Select the File | Page Setup option from the
DatabaseName DBDEMOS
Report Designer main menu.
Name tblCustomer
TableName customer.db 4 Click the Paper Size tab and change the paper
orientation from Portrait to Landscape, then click
4 Add a DataSource component to the form.
the OK button.
5 Configure the DataSource component:
Lay Out the Customer List Title Label in
DataSet tblCustomer the Header Band
Name dsCustomer 1 Right-click over the white space of the header
band and access the Position... dialog.
6 Select the RBuilder tab of the Delphi compo-
nent palette. 2 Set the height to 0.9167 and click the OK but-
ton. The header band should expand in height.
7 Add a DBPipeline component to the form.
Note: You can also change the height of the header
8 Configure the DBPipeline component: band by dragging the divider that appears below
the white space of the header band. This method is
DataSource dsCustomer
quick and easy, but not as precise.
Name plCustomer
Create a Report and Connect it to the 3 Click the Label component icon on the
Data Report Designer component palette.
6 Select the text inside it and replace it with Cus- 14 Click the OK button. The label should move to
tomer List. the upper left corner of the header band.
7 Locate the font controls on the Format bar. Note: You can also change the position of a com-
ponent by dragging it. The exact position of the
Note: The font controls appear to the right of the
component will be displayed in the status bar at the
Edit box and provide the following functions:
bottom of the Report Designer after it is dropped.
• Font Name drop-down list You can use any unit of measure (inches, screen
• Font Size drop-down list pixels, millimeters, etc.) you prefer.
• Bold
• Italic
layout check
• Underline Font Style
• Text Alignment
• Font color
• Highlight color Lay Out the Company Title Label in the
8 Set the font: Header Band
1 Place another label near the center of the header
Font Name Times New Roman band.
Font Size 12
2 Configure the label:
Font Style Bold & Italic
Caption Marine Adventures &
9 Locate the horizontal ruler. It is above the
Sunken Treasures Co.
header band.
Font Name Times New Roman
10 Position the mouse over the ruler and right-
Font Size 16
click.
Font Style Bold & Italic
11 Select the Millimeters option from the speed
menu. 3 Click the font color drop-down icon and
select dark blue.
12 Right-click over the label and select the Posi-
tion... menu option. 4 Select View | Toolbars from the Report
Designer main menu. A list of toolbar names
13 Enter the following values into the Position dia-
should be displayed. Select the Align or Space
log:
toolbar.
Left 2.381
5 Click on the label component that you just cre-
Top 1.323
ated in the header band.
Width 24.871
Height 5.027
A Simple Report the Hard Way
250 REPORT TUTORIALS
layout check
aligned.
layout check
7 Hold down the Ctrl key and press the down 6 Place five more DBText components in the
arrow key until the line is positioned at the bottom detail band. Assign them to the following fields:
of the header band.
Contact
Phone
layout check
Addr1
City
State
Lay Out the Detail Band 7 Right-click over the horizontal ruler and change
1 Click the DBText component icon on the the unit of measure to Screen Pixels.
Report Designer component palette. 8 Right-click over the DBText component
2 Click in the detail band. A DBText component assigned to the Company field and access the Posi-
will be created. tion... dialog. Set the position values:
Font Name Times New Roman 10 Select the Company DBText component, then
Font Size 10 Shift-click to select the remaining DBText compo-
Font Style Regular nents.
Font Color Black 11 Click on the Align Top icon of the Align or
Space toolbar. The components should align with
Company DBText component.
13 Right-click over the white space of the detail Align the Header Band Labels with the
band and access the Position... dialog. Detail Band DBText Components
1 Select the Company DBText component in the
14 Set the height to 25. The detail band should
detail band.
shrink in height.
2 Hold down the Shift key and click on the Com-
pany label component in the header band.
layout check
Contact
layout check
Phone
Address
City
State Set PrintDateTime
1 Right-click over the white space of the footer
4 Click the Align Top icon on the Align or Space band and access the Position... dialog.
toolbar. The labels should align with the top of the
Company label. 2 Set the height to 40. The footer band should
shrink in height.
6 Select the PrintDateTime item from this list. 5 Use the drop-down list on the left-hand side of
The current date and time will be displayed in the the Report Designer to select the PageSetDesc
component. variable type. Page 1 of 1 should be displayed in
the component.
7 Set the font:
6 Right-click over the component and access the
Font Name Times New Roman
Position... dialog.
Font Size 10
Font Style Regular 7 Set the position values:
Font Color Black
Left 943
8 Right-click over the SystemVariable component Top 22
and access the Position... dialog.
8 Right-justify the component by clicking on the
9 Set the position values: Right Justify icon on the Format toolbar.
3 Configure the Query component: 3 Set the paper orientation to Landscape (File |
Page Setup | Paper Size).
DatabaseName DBDEMOS
SQL SELECT * 4 Drag the header band to the one inch mark on
FROM master the vertical ruler. Right-click over the white space
ORDER BY rcmndation of the header band and access the Position dialog.
Name qryStock The value for the height should be 1.
4 Double-click on the Active property in the Create Labels in the Header Band
Object Inspector to set it to true. 1 Place a label in the left side of the header band.
5 Add a DataSource component to the form. 2 Set the caption to Gekko Investments.
DataPipeline plStock
Name rbStock
257
Groups, Calculations, and the Summary Band
REPORT TUTORIALS
8 Set the font and position: Note: Because groups are based on a change in
field value, the field on which a group is based
Font Name Times New Roman
should always be used to order the records. You
Font Size 12
may remember that the query for this report is
Font Style Bold & Italic
ordered by the 'rcmndation' field. You must always
Left 0.0417
order the records by the fields you intend to use for
Top 0.4063
groups because ReportBuilder will not sort records
for you.
layout check
Left 0.0417
Top 0.0937
Groups, Calculations, and the Summary Band
258 REPORT TUTORIALS
4 Place a line component near the bottom of the Code the BeforeGenerate Event of the
group header band. Group Header Band
1 Click in the white space of the group header
5 Right-click over the line component and select
band. The band should be selected in the Object
the ParentWidth option.
Inspector.
6 Locate the Line type drop-down list at the upper
2 Click on the Events tab of the Object Inspector
left corner of the Report Designer.
and double-click on the BeforeGenerate event.
7 Select 'Bottom' from this list. This causes the Add the code shown below to the event handler.
line to be drawn at the bottom of the rectangular
Note: This routine retrieves the value of the rec-
bounding shape.
ommendation field into a local string variable. It
8 Click on the Line thickness icon on the then assigns a color based on the value of the field.
Draw toolbar and select 1 1/2 point. The color is stored in a private variable of the form
so that all of the report event handlers can use it.
9 Select the line and use the arrow keys to posi-
The recommendation label in the group header
tion it so that it's flush with the bottom of the group
band is set to the color. Finally, the recommenda-
header band.
tion label caption is set using the FirstPage prop-
erty of the group. If FirstPage is False, then the
group has overflowed onto an additional page.
layout check
3 Scroll up in the Code Editor and add the follow- Add General Data to the Detail Band
ing code to the 'private' section of the form class 1 Access the Report Designer.
declaration:
2 Right-click over the white space of the detail
FRecommendationColor: TColor; band and select the Position... menu option.
4 Select View | Toggle Form/Unit from the Delphi 3 Set the height to 1.8542.
main menu.
4 Select View | Toolbars | Data Tree. The Data
5 Select the Standard tab of the Delphi Compo- Tree window should appear. Position it over the
nent palette. Object Inspector.
6 Create a button on the form. 5 Click the Layout tab at the bottom of the Data
Tree and configure the drag-and-drop settings:
7 Configure the button:
Create All
Name btnPreview
Style Tabular
Caption Preview
Label Grid False
8 Add the following code to the OnClick event for
Label Font Name Times New
the button:
Label Font Style Regular
rbStock.Print; Label Font Size 10 point
Label Font Color Black
9 Select File | Save from the Delphi main menu.
Field Grid False
10 Run the project. The report should look like
Field Font Name Times New
this:
Field Font Style Bold
Field Font Size 10 point
Field Font Color Black
EXCHANGE
INDUSTRY
PROJ_GRTH
OUTLOOK
Groups, Calculations, and the Summary Band
260 REPORT TUTORIALS
7 Drag the selected fields into the detail band. 13 Select the line, then Shift-click the label. Click
Four DBText components and four associated the Align Middle icon on the Align or Space
labels will be created. toolbar.
8 Hold down the Ctrl key and use the arrow keys
to position the selection:
Left 1.0729
Top 0.3542
layout check
Note: As you move the selection, the position
appears on the status bar. Use these measurements
to determine when you have reached the position.
9 Place a line above the selection. Add the Vital Stats Data to the Detail
Band
10 Configure the line component:
1 Use the Ctrl-click method to select these fields
Line Type Top in order from the Data Tree:
Thickness 1 1/2 pt
P_E_RATIO
Left Position 1.0729
RANK
Top 0.2083
RATING
Width 4.2604
BETA
11 Place a label component over the line.
2 Drag the selected fields directly below the Gen-
12 Configure the label component: eral components. Four DBText components and
four associated labels will be created.
Caption General
Font Name Times New Roman 3 Hold down the Ctrl key and use the arrow keys
Font Size 10 to position the selection:
Font Style Bold & Italic
Left 1.0729
Text Alignment Centered
Top 1.1875
Top Position 0.1354
Transparent False 4 Select the line and General label.
7 Set the line top to 1.0417. 3 Hold down the Ctrl key and use the arrow keys
to position the selection:
8 Set the label top to 0.9687.
Left 5.7188
9 Right-click over the label and select the Bring to
Top 0.3542
Front menu item.
4 Right-click over each of the four DBText com-
10 Set the label caption to Vital Stats.
ponents and set the DisplayFormat to
11 Select the PE RATIO label, then Shift-click the $#,0.00;($#,0.00) (the first selection with a dollar
line. sign).
12 Click the Align Left icon of the Align or 5 Select the line and General label.
Space toolbar. 6 Copy and paste the selection.
13 Select the line, then Shift-click the Vital Stats 7 Position the selection above the newly-created
label. components.
14 Click on the Align Middle icon of the Align 8 Set the label caption to Pricing.
or Space toolbar.
layout check
layout check
2 Drag the selected fields to the immediate right 5 Click on the Align Top icon of the Align or
of the General components. Four DBText compo- Space toolbar.
nents and four associated labels will be created.
Groups, Calculations, and the Summary Band
262 REPORT TUTORIALS
6 Select the line behind the General label, then the 5 Click in the white space of the band to deselect
line behind the Pricing label. the components, then select the DBText component
for the RCMNDATION field.
7 Click the Align Top icon.
6 Set the name of this component to dbtRecom-
8 Select the Pricing line and then the Pricing
mendation in the Object Inspector. We will use this
label.
name in an event handler.
9 Click on the Align Middle icon of the Align 7 Select the Pricing line and label.
or Space toolbar. The label should be centered hor-
izontally in relation to the line. 8 Copy and paste the selection.
layout check
6 Click the Align Top icon of the Align or 3 Place another DBText component in the upper
Space toolbar. left corner of the detail band.
7 Select the Recommendation line and label. 4 Configure the DBText component:
DataField CO_NAME
8 Click on the Align Middle icon of the Align
Name dbtCompany
or Space toolbar. The label should be centered hor-
Font Name Times New Roman
izontally in relation to the line.
Font Size 8
Font Style Regular
Left 0
Top 0.4167
Width 1
layout check
Note: This routine sets the color of the stock sym- 6 Configure the SystemVariable component:
bol and the recommendation field to the color as
VarType PageSetDesc
defined in the BeforeGenerate event of the group
Text Alignment Right justified
header band.
Font Name Times New Roman
5 Select File | Save from the Delphi main menu. Font Size 10
Font Style Regular
6 Select Project | Compile rbSTProj from the Del-
Font Color Black
phi main menu. Fix any problems.
Left 9.75
7 Run the project. Top 0.2292
8 Preview the report. Click on the Last Page icon 7 Select File | Save from the Delphi main menu.
of the Print Preview window. A thirty-seven page
8 Preview the report by running the application.
report should appear. The label in the group header
should change color based on the group. The stock PrintDateTime
symbol and recommendation fields should also be
color-coded.
Left 0
Top 0.0313
Adjust the Summary Band Labels 9 Click on the Sell label, then Shift-click the new
1 Place the Buy label at the following position: label.
Top 2.0104
layout check
5 Click the Space Vertically icon on the Align
or Space toolbar.
Caption Total Number of 3 Use the drop-down list in the Edit toolbar to set
Stocks Analyzed the DataType of each of the variables to Integer.
Font Name Times New Roman
4 Select the vrBuyTotal variable and set the posi-
Font Size 16
tion:
Font Style Regular
Top Position 2.4896 Left 3.5521
7 Click the Right Justify icon on the Format tool- Assign Event Handlers to the OnCalc
bar. Events of the Variable Components
1 Select the vrBuyTotal variable.
8 Select the Buy label, then Shift-click the vrBuy-
Total variable. 2 Click on the Events tab of the Object Inspector.
9 Click the Align Top icon of the Align or 3 Double-click on the OnCalc event. An event
Space toolbar. Align the Hold and Sell variables handler shell will be generated in your Delphi
with the corresponding labels. form.
10 Select the Buy label and variable and set the 4 Assign the following code to this event handler:
font color to green. if(qryStock.FieldByName('Rcmndation').AsString
ª = 'BUY') then
11 Select the Hold label and variable and set the Value := Value + 1;
font color to olive. 5 Assign the following code to the OnCalc event
12 Select the Sell label and variable and set the font of the vrHold variable:
color to maroon. if(qryStock.FieldByName('Rcmndation').AsString
ª = 'HOLD') then
13 Select File | Save from the Delphi main menu. Value := Value + 1;
8 Select Project | Compile rbSTProj from the Del- 6 Click on the vrSellTotal variable, then Shift-
phi main menu. Fix any problems. click the DBCalc component.
9 Run the project. 7 Click on the Align Right icon of the Align
10 Preview the report. Click on the Last Page icon or Space toolbar.
of the Print Preview window. A thirty-eight page 8 Select the Total... label, then the DBCalc com-
report should appear. The summary band should ponent.
contain totals for each recommendation type.
9 Click on the Align Top icon of the Align or
Note: You must compile and run this report in
Space toolbar.
order to see exactly what it will look like. This is
because event handlers have been assigned to the 10 Place a line component at the bottom of the
report. When event handlers are assigned, the summary band.
report must be compiled and run; otherwise, the
11 Right-click over the line component and select
event handler code will not be used when generat-
the Double menu option. The line should now
ing the report and any changes made via the event
appear as two parallel lines.
handlers will not be reflected in the report.
12 Set the top of the line to 2.3437.
Create the Grand Total
1 Return to the Report Designer. 13 Select the DBCalc component, then Shift-click
the line.
2 Place a DBCalc component at the bottom of
the summary band. 14 Select the View | Toolbars | Size menu option
from the Report Designer main menu.
3 Right-click over the component and access the
Calculations... menu option. 15 Dock the Size toolbar on the lower left side of
the Report Designer.
4 Select the Count function from the Calc Type
drop-down list and click the OK button. 16 Click on the Grow Width to Largest icon of
the Size toolbar. The line should now be the same
5 Configure the component:
width as the DBCalc.
Font Name Times New Roman
Font Size 16 17 Click the Align Right icon on the Align or
Font Style Bold Space toolbar.
Font Color Black
Text Alignment Right justified
Width 1.0729
269
Groups, Calculations, and the Summary Band
REPORT TUTORIALS
18 Select File | Save from the Delphi main menu. Last Page
layout check
Preview at Run-Time
1 Select Project | Compile rbSTProj. Fix any
compilation problems.
First Page
271
Using Regions to Logically Group Dynamic Components
REPORT TUTORIALS
3 Configure the Table component: 3 Set the paper orientation to Landscape (File |
Page Setup | Paper Size).
DatabaseName DBDEMOS
Name tblBiolife 4 Click the Layout tab of the Page Setup dialog
TableName biolife.db and set the Columns to 2.
4 Select the Table component and then double- 5 Click the OK button to close the dialog.
click on the Active property in the Object Inspector
Configure the Header and Footer
to set it to true.
Bands
5 Add a DataSource component to the form. 1 Set the height of the header and footer bands to
0.3.
6 Configure the DataSource component:
2 Scroll to the right in the Report Designer until
DataSet tblBiolife
you can see the right edge of the bands.
Name dsBiolife
3 Place a SystemVariable component on the right
7 Select the RBuilder tab of the Delphi compo-
side of the footer band.
nent palette.
4 Locate the drop-down list at the upper left cor-
8 Add a DBPipeline component to the form. ner of the Report Designer.
9 Configure the DBPipeline component: 5 Select the PrintDateTime option from the drop-
down list.
DataSource dsBiolife
Name plBiolife
DataPipeline plBiolife
Name rbRegions
273
Using Regions to Logically Group Dynamic Components
REPORT TUTORIALS
6 Configure the component: Note: You may notice that the group header and
group footer bands created for the Category group
Font Name Arial
are the same width as the column header, column
Font Size 12
footer, and detail bands. This is due to the fact that
Font Style Regular
group bands print before and after the detail band.
Font Color Black
In order to print before and after the detail band,
Left 8.9583 the group bands must be the same width as the
Top 0.0833 detail band.
Text Alignment Right justified
layout check
Create a Memo Region 6 Select File | Save from the Delphi main menu.
1 Place a region immediately below the image
Note: By setting the Stretch property to True, we
region.
are telling the Memo to expand or contract based
2 Configure the region: on the amount of text in the Notes field. The text
will be wrapped within the width of the compo-
Name rgMemo
nent. The Bottom Offset property determines the
Left 0
amount of white space that will appear below the
Top 1.8021
memo after it has completed printing.
Width 4
Height 0.4687
4 Drag the Notes field from the Data Tree into the
white space of the memo region.
6 Select the following fields and then drag the Note: We set the Stretch property of the DBMemo
selection into the fields region: component to True. That means that each time the
memo prints, the height will expand or contract
Category
based on the amount of text in the Notes field.
Common_Name
Because the memo is contained within a region,
Species Name
that region will also stretch to accommodate the
Length_In
memo. When that happens, we want to position the
7 Hold down the Ctrl key and use the arrow key to fields containing the DBText components immedi-
position the selection: ately below the Memo region. We do this by set-
ting the ShiftRelativeTo property of the Fields
Left 0.1771
region to the Memo region.
Top 2.4166
6 Select File | Save from the Delphi main menu.
8 Close the Data Tree.
7 Close the Report Designer.
layout check
layout check
277
Using Regions to Logically Group Dynamic Components
REPORT TUTORIALS
Add a Color-Coding Event Handler 3 Add the following code to the OnDestroy event
1 Add the following variable to the private section of the form:
of the form:
procedure TfrmRegions.FormDe-
stroy(Sender: ªTObject);
FColors: TList; begin
FColors.Free;
2 Add the following code to the OnCreate event end;
of the form:
if not(rbRegions.DetailBand.OverFlow) then
begin
lColor := TColor(FColors[plBiolife.TraversalCount]);
rgFields.Brush.Color := lColor;
dbmNotes.Font.Color := lColor;
end;
end;
Note: This event handler sets the color of the 5 Select Project | Compile rbRGProj. Fix any
Fields region and the Memo font. The colors were compilation problems.
hand-picked to match the bitmap images. Because
6 Select File | Save from the Delphi main menu
there is only one record per column, the DataPipe-
line.TraversalCount property (which tracks the 7 Run the project..
number of records traversed) can be used to map
the color from the TList object to the column.
DataPipeline plCustomer
Name rbFormEmu
Note: This event handler executes every time the 4 Select Report | Footer from the Report Designer
record position of the customer table changes. Cal- main menu. The footer band will be removed.
culations placed in this event must always be intra-
record, which means that the values must be calcu- 5 Click the report selection icon located at the
lated from other values in the current record or intersection of the horizontal and vertical rulers.
must be hard-coded (as in this case). The report will be selected in the Object Inspector.
10 Double-click the DBPipeline component to dis- 6 Expand the PrinterSetup property and set all of
play the Field Editor. the margins (MarginTop, MarginBottom, etc.) to
zero.
11 Check to make sure that the calculated fields are
listed. If they are not, then close the Field Editor; 7 Set the height of the detail band to 11.
set the AutoCreateFields property to False in the Create an Image Component
Object Inspector, then set it back to True. Launch
1 Place an image component on the left side
the Field Editor again and make sure the new fields
of the detail band.
are listed.
2 Configure the Image component:
Note: Toggling the AutoCreateFields property for
the DBPipeline will refresh the field list whenever Center False
you've changed the fields in the dataset. DirectDraw True
MaintainAspectRatio True
12 Select Project | Compile rbFEProj from the Del-
Stretch True
phi main menu. Fix any compilation errors.
Note: We want the image to be scaled because it's
13 Select File | Save from the Delphi main menu.
a little too big to fit on the page, despite the zero
Configure the Page Size and Bands margins. We do not want to distort the form in any
1 Double-click on the Report component to dis- way, so MaintainAspectRatio has been set to True.
play the Report Designer. Center is not needed because we want to print the
form at a position of 0,0 (this form image already
2 Size and move the Report Designer window so
contains white space around the edges). Finally, the
that the Object Inspector is visible.
DirectDraw property will force the image to be
3 Select Report | Header from the Report printed directly to the printer without utilizing an
Designer main menu. The header band will be intermediate canvas, which usually results in
removed. higher quality output.
Forms Emulation with a WMF Image
284 REPORT TUTORIALS
3 Right-click over the Image component and 4 Click the Data tab. Select the following fields
select the Picture... menu option. in order:
2 Position the Data Tree to the left of the Report 10 Click on the DisplayFormat property in the
Designer (in front of the Object Inspector). Object Inspector. The selected DisplayFormat
should appear. Paste the DisplayFormat into this
3 Click on the Layout tab of the Data Tree and
field and then click off of the property.
configure it:
11 Click on the Image and then click on each of the
Create Fields
DBText components in succession, checking to
Style Vertical
make sure that the DisplayFormat has been set.
Field Font Name Courier New
12 Set the position of the Wages DBText compo-
Field Font Style Regular
nent:
Field Font Size 10
Field Font Color Black Left 4.375
Top 0.8021
285
Forms Emulation with a WMF Image
REPORT TUTORIALS
13 Set the position of the SSWages DBText com- 7 Click on the image to deselect the components.
ponent:
8 Select the newly created Wages DBText compo-
Left 4.375 nent and set the field to FederalTaxWithheld.
Top 1.1146
9 Select the SSWages DBText component and set
14 Set the position of the MedicareWages DBText the field to SSTaxWithheld.
component:
10 Select the MedicareWages DBText component
Left 4.375 and set the field to MedicareTaxWithheld.
Top 1.4271
layout check
layout check
6 Right-click over the memo and access the 17 Position the label:
Lines... menu option. Enter the following text into
Left 4.2917
the Memo Editor:
Top 3.4583
Digital Metaphors Corporation
16775 Addison Rd., Suite 613
Addison, TX 75001
layout check
8 Copy and paste the selection.
Write the 'address squeeze' Routine 6 Scroll up to the form class declaration. Replace
1 Close the Report Designer. the private declarations comment with the follow-
ing procedure declaration:
2 Locate the drop-down list of components at the
top of Object Inspector. procedure BuildEmployeeAddress(aStrings:
ª TStrings);
3 Select the Detail band in this list (it should be
named ppDetailBand1). 7 Scroll down below the DetailBand BeforeGen-
erate event handler and insert the code shown
4 Select the Events tab and double click on the
below as the BuildEmployeeAddress procedure.
BeforeGenerate event.
Note: In this event handler we need to build the
5 Place the following code in the event handler:
same address for two different memo compo-
BuildEmployeeAddress(mmEmployeeAddress1.Lines);
BuildEmployeeAddress(mmEmployeeAddress2.Lines);
nents. In order to accomplish this, we can create a
general routine (BuildEmployeeAddress) that we 8 Click on the Preview button. The report should
can call for each component, or we can build the be displayed in the Print Preview form. The report
address in a local string variable and then assign it should look like this:
to both components. We chose the latter approach
for readability.
Name btnPreview
Caption Preview
• Configure Delphi data access objects for use as a 3 Select File | Save As from the Delphi menu and
lookup table save the form under the name rbMD in the My RB
Tutorials directory (established on page 181).
• Use a subreport to print detail data
Note: It is important to name the form and save the
• Define a group break
form's unit using the names given above because
the report will be used in later tutorials.
DataSet tblEmployee
7 Add a DBPipeline component to the form.
Name dsEmployee
8 Configure the DBPipeline component:
4 Configure the DBPipeline component:
DataSource dsCustomer
DataSource dsEmployee
Name plCustomer
Name plEmployee
Create the Table, DataSource, and Define the Relationship between the
DataPipeline for the Detail Table Customer and Order Table
1 Add a second set of Table, DataSource, and
1 Select the Order table component.
DataPipeline components to your form.
2 Set the MasterSource property to dsCustomer.
2 Configure the Table component:
3 Select the MasterFields property and click the
DatabaseName DBDEMOS
“...” button. This displays the Field Link Designer.
Name tblOrder
TableName orders.db
Master Detail Report
REPORT TUTORIALS 291
4 Click on the Available Indexes drop-down list 5 Select the EmpNo field in the Master Fields list.
and select CustNo.
6 Click the Add button. A new item (EmpNo
5 Select the CustNo in the Detail Fields list. EmpNo) will be added to the Joined Fields list.
6 Select the CustNo item in the Master Fields list. 7 Click the OK button to close the dialog.
7 Click the Add button. A new item (CustNo 8 Select File | Save from the Delphi main menu.
CustNo) will be added to the Joined Fields list.
Note: In this example you will notice the fields
8 Click the OK button to close the dialog. being linked have the same name. This is a good
standard to follow when designing a database.
Note: The IndexName property is now set to
However, it is not a requirement for linking fields.
CustNo. This property was automatically set when
we selected the CustNo index in step 4 above. Create a Report and Connect it to the
Data
Note: To establish a master detail relationship,
the detail table must be indexed on the linking field 1 Add a Report component to the form.
value or values. You can think of an Index as
2 Configure the Report component:
defining the sort order for the table. Thus, if we
need to link the Order table to the Customer table DataPipeline plCustomer
based on CustNo, the Order table must have an Name rbOrderSummary
index (i.e. sort order) based upon CustNo.
3 Double-click on the Report component to dis-
Define the Relationship between the play the Report Designer.
Order and Employee Table
4 Position the Report Designer so that the Object
1 Select the Employee table component.
Inspector is visible.
2 Set the MasterSource property to dsOrder.
5 Place a subreport component (from the
3 Launch the Field Link Designer from the Mas-
Advanced toolbar) in the detail band.
terField property.
Note: When you add the subreport, two tabs will
4 Select the EmpNo item field in the Detail Fields
be displayed at the bottom of the workspace: Main
list.
and SubReport1. There is a separate workspace for
the main report and for each subreport. You can
access the workspace for any given report by click-
ing on the tab.
Master Detail Report
292 R EPORT TUTORIALS
6 Use the Object Inspector to set the DataPipeline Create the Header Band Labels
property of the subreport to plOrder. 1 Set the height of the header band to 2.5 inches.
Note: When we initially set the DataPipeline prop- 2 Place a label in the upper left corner of the
erty of the main report to the customer table, we header band.
were telling the report to print one detail band for
3 Configure the label:
each customer. Now that we have set the
DataPipeline property of the subreport, we're tell- Caption Order Summary
ing the subreport to traverse all orders for each cus- Font Name Times New Roman
tomer, printing one detail band for each order. Font Size 12
Font Style Bold & Italic
7 Select Report | Data from the main menu.
plCustomer should be selected as the data pipeline. 4 Place another label at the top center of the
header band.
Note: The Data dialog can be used as a convenient
way to set the DataPipeline property of a report. 5 Configure the label:
8 Position the subreport at the top of the detail Caption Marine Adventures &
band. Sunken Treasure Co.
9 Drag the the detail band divider up until it is Font Name Times New Roman
flush with the bottom of the subreport. Font Size 16
Font Style Bold & Italic
Font Color Navy
Text Alignment Centered
layout check
6 Hold down the Ctrl key and use the arrow keys 4 Click the Start New Page and Reset Page Num-
to position the selection: ber check boxes near the middle of the dialog. This
will cause the listing for each customer to start on a
Left 0.1458
new page and appear with its own page numbers.
Top 1.1875
Note: Because groups are based on a change in
7 Click in the white space of the header band to
field value, the field on which a group is based
deselect the components.
should always be used to order the records.
8 Select the CustNo label, then Shift-click the cor- ReportBuilder does not sort records; therefore, you
responding DBText component. Click on the Left must order the records using an Index or by speci-
Justify icon on the Format toolbar. fying an Order By clause in an SQL query.
9 Right-click over the Company DBText compo- 5 Click the OK button. You should see two new
nent and set the AutoSize property to True. bands: one above and one below the detail band.
These bands have no height; thus, no white space
10 Right-click over the CustNo DBText component
appears above the dividers.
and set the AutoSize property to True.
6 Select File | Save from the Delphi main menu.
layout check
layout check
3 Use the Draw toolbar to set the Fill and Line 11 Left justify all of the components.
color of the shape to Navy. 12 Right-click over the SaleDate DBText compo-
4 Right click over the shape to display the popup nent and set the DisplayFormat to 'mm/dd/yyyy'.
menu. Select the ParentHeight and ParentWidth Note: The Display Format dialog automatically
options. The shape will resize and cover the entire checks the data type of the component and displays
band. a list of appropriate formats.
5 Click the Layout tab at the bottom of the Data 13 Set the width of the Date label and the corre-
Tree and configure the drag-and-drop settings: sponding DBText component to 0.8.
Create All 14 Select the DBText components and move them
Style Tabular to a top position of 0.0521.
Label Font Name Times New
Label Font Style Bold
layout check
Complete the Order Information Layout 9 Place a label directly on top of the shape, posi-
1 Select the plEmployee DataPipeline in the Data tioning it near the shape's midpoint.
Tree.
10 Configure the label:
2 Drag the FirstName field into the title band,
AutoSize False
positioning the mouse to the immediate right of the
Date label. Caption Order
6 Place a shape component in the left side of the 11 Select the white shape, then Shift-click the
title band. Order Label. Click on the Align Middle and
7 Align the left edge of the shape with the Num- Align Center icons of the Align or Space tool-
ber label and stretch the width until the right edge bar.
is flush with the right edge of the Sales Rep label.
12 Select File | Save from the Delphi main menu.
8 Configure the shape:
13 Click the Preview tab to view the report. Click
Top 0.1 the next page buttons to preview several pages.
Height 0.08 When you are done previewing, return to the
Fill Color White Design workspace.
Line Color White
layout check
Master Detail Report
REPORT TUTORIALS 297
Lay Out the Shipping Information 14 Select the shape component, then Shift-click the
Components Ship label. Click on the Align Middle and
1 Select the plOrder DataPipeline in the Data Tree
Align Center icons of the Align or Space tool-
and select the following fields in order:
bar.
ShipVia
15 Select File | Save from the Delphi main menu.
ShipDate
Preview as desired.
2 Drag the selection into the title band, to the
immediate right of the Sales Rep label. Position
layout check
the selection:
Left 3.875
Top 0.2813
Lay Out the Payment Information
3 Align the top of the new DBText components
Components
with the top of the existing components.
1 Select the plOrder DataPipeline in the Data Tree
4 Set the label captions to Via and Date. and select the following fields in order:
6 Set the Display Format of the Date DBText 2 Drag the selection into the title band, to the
component to 'mm\dd\yyyy'. immediate right of the ShipDate label. Position the
selection:
7 Select the Order label, then Shift-click the white
shape behind it. Left 5.5833
Top 0.2813
8 Copy and paste the selection.
3 Align the top of the new DBText components
9 Position the new components above the Via and
with the top of the existing components.
Date labels.
4 Set the label captions to Method and Amount.
10 Set the position and size of the shape:
5 Set the DisplayFormat of the Amount DBText
Left 3.8333
component to $#,0.00;($#,0.00) (the first format
Width 1.61
with a dollar sign).
11 Align the top of the new shape with the top of
6 Right justify the text in the Amount label.
the existing shape.
7 Select the Ship label, then Shift-click the white Complete the Detail Band
shape behind it. 1 Place a Line component in the upper left corner
of the detail band.
8 Copy and paste the selection.
2 Locate the Line Position drop-down list at the
9 Drag the new components to the right, aligning
upper left of the Report Designer.
the left edge of the shape with the left edge of the
Method label. 3 Select Left from this list. A vertical line will
appear on left side of the line component.
10 Align the top of the new shape with the top of
the existing shapes. 4 Configure the Line:
4 Place a line directly below the DBCalc compo- 10 Align the top of the DBText component with the
nent. top of the label.
5 Configure the Line: 11 Place a line component in the upper left corner
of the summary band. Configure the line:
Position Bottom
Style Double ParentWidth True
Top 0.25 Line Color Navy
Width 1.18 Line Thickness 2 1/4 point
Height 0.05 Top 0
Height 0.05
6 Hold down the Ctrl key and use the right arrow
key to align the right edge of the line with the right 12 Select File | Save from the Delphi main menu.
edge of the DBCalc. Preview as desired.
layout check
Master Detail Report
300 R EPORT TUTORIALS
Lay Out the Footer Band 12 Select File | Save from the Delphi main menu.
1 Click on the 'Main' tab to return to the main Preview the completed report.
report.
layout check
4 Set the left position to 0.0625.
2 Configure the Table component: 7 Click the Add button. A new item (OrderNo
OrderNo) will be added to the Joined Fields list.
DatabaseName DBDEMOS
Name tblItem 8 Press the OK button to close the dialog.
TableName items.db
Note: The IndexName property is now set to
3 Add a DataSource component to the form. ByOrderNo. This property was set automatically
when we selected the ByOrderNo index in step 4
4 Configure the DataSource component:
above. To establish a master detail relationship,
DataSet tblItem the detail table must be indexed on the linking field
Name dsItem value or values. You can think of an Index as
defining the sort order for the table. Thus, if we
5 Select the RBuilder tab of the Delphi compo-
need to link the Items table to the Order table based
nent palette.
on OrderNo, the Items table must have an index
(i.e. sort order) based upon OrderNo.
6 Add a DBPipeline component to the form.
DataSource dsItem
Name plItem
Master Detail Detail Report
REPORT TUTORIALS 305
Create the Table, DataSource and Note: In this example you will notice the fields
DataPipeline for the Parts Lookup Table being linked have the same name. This is a good
1 Add a Table component to your form. standard to follow when designing a database.
However, it is not a requirement for linking fields.
2 Configure the Table component:
8 Select File | Save from the Delphi main menu.
DatabaseName DBDEMOS
Name tblPart Update the Report Title
TableName parts.db 1 Access the Report Designer.
3 Add a DataSource component to the form. 2 Locate the Order Summary label in the upper
left corner of the header band.
4 Configure the DataSource component:
3 Set the caption to Order Detail.
DataSet tblPart
Name dsPart Create SubReport2 and Connect it to
the Data
5 Select the RBuilder tab of the Delphi compo-
1 Click the 'Subreport1' tab.
nent palette.
2 Right-click over the vertical line component
6 Add a DBPipeline component to the form. located at the extreme left of the detail band.
Select the StretchWithParent and ReprintOnOver-
7 Configure the DBPipeline component:
flow menu options.
DataSource dsPart
3 Right-click over the vertical line component at
Name plPart
the far right of the detail band. Select the Stretch-
Define the Relationship Between the WithParent and ReprintOnOverflow menu options.
Item and Parts Table
Note: The detail band will contain a child-type
1 Select the Part table component.
subreport that will stretch to print all of the items
2 Set the MasterSource property to dsItem. for the current order. By setting StretchWithParent
to True, we are saying “Whatever the height of the
3 Launch the Field Link Designer from the Mas-
detail band is in the report, resize the line to match
terFields property.
it.” Sometimes the items for an order will overflow
4 Select the PartNo in the Detail Fields list. onto an additional page. By setting Reprint-
5 Select the PartNo in the Master Fields list. OnOverFlow to True we are saying “When the
detail band overflows onto an additional page,
6 Click the Add button. A new item (PartNo make sure to reprint the line.”
PartNo) will be added to the Joined Fields list.
4 Set the height of the detail band to 0.4687. Note: Within the context of a child subreport, the
title band would print once at the beginning of the
5 Place a subreport component just below the report and the summary band would print once at
DBText components in the detail band. the end. This would be fine for our purposes
6 Right-click over the subreport and set Parent- except that all of the items for a particular order
Width to false, then set the position: may not fit on a single page, and so the subreport
may overflow onto additional pages. When this
Left 0.875
happens, we want to reprint the header labels for
Top 0.2708
the item fields. The ReprintOnSubsequent prop-
Width 6.25
erty of Group Header bands will work nicely for
7 Use the drop-down list at the upper left corner this requirement, so we will be using a group
of the Report Designer to set the subreport's header and group footer band instead of the title
DataPipeline to plItem. and summary band.
layout check
layout check
new entry entitled Group[0]: plItem.OrderNo will
be added to the list.
Begin Laying Out the Items Information 7 Left justify the components.
Components for the SubReport
8 Set the label caption to Item No.
1 Select View | Toolbars | Data Tree from the
Report Designer menu. Position the Data Tree to 9 Select the plPart data pipeline in the Data Tree.
the left of the Report Designer.
10 Select the Description field.
2 Click the Layout tab at the bottom of the Data
11 Drag the selection into the group header band,
Tree and configure the drag-and-drop settings as
positioning the mouse to the immediate right of the
follows:
Item No. label. Release the mouse button. A
Create All DBText component and corresponding label will
Style Tabular be created.
Label Font Name Times New Roman 12 Hold down the Ctrl key and use the arrow keys
Label Font Style Bold to position the selection:
Label Font Size 10 point
Left 1.125
Label Font Color White
Top 0.1354
Field Font Name Times New Roman
13 Hold down the Shift key and use the left arrow
Field Font Style Regular
key to decrease the width of both components to
Field Font Size 10 point
1.7083.
Field Font Color Black
14 Set the top of both DBText components in the
3 Click on the Data tab and then select the plItem
detail band to 1.6667.
data pipeline from the list at the top.
6 Hold down the Ctrl key and use the arrow keys
to position the selection:
Left 0.1042
Top 0.1354
Master Detail Detail Report
REPORT TUTORIALS 309
Complete the Items Information Layout 15 Configure the label:
1 Select the Qty field of the plItem data pipeline
AutoSize False
in the Data Tree.
Caption Item Total
2 Drag the selection to the immediate right of the Font Name Times New Roman
Description label. Font Size 10 point
Font Style Bold
3 Position the selection:
Font Color White
Left 2.8646 Left 4.8646
Top 0.1354 Top 0.1354
Width 0.9792
4 Right justify the components.
Text Alignment Right justified
5 Set the label caption to Quantity.
16 Place a variable component in the detail band
6 Align the top of the new DBText with the top of just below the Item Total label.
the existing DBText components.
17 Configure the variable component:
7 Select the List Price field of the plPart data pipe-
Name vrItemTotal
line.
DataType dtCurrency
8 Drag the selection to the immediate right of the Font Name Times New Roman
Quantity label. Font Size 10 point
9 Position the selection: Font Style Regular
Font Color Black
Left 3.8646 Text Alignment Right
Top 0.1354 DisplayFormat $#,0.00;($#,0.00)
10 Right justify the components. Width 0.9792
11 Set the label caption to List Price. 18 Select the Item Total label, then Shift-click the
vrItemTotal variable. Click the Align Right icon
12 Set the Display Format of the DBText compo-
on the Align or Space toolbar.
nent to $#,0.00;($#,0.00).
19 Align the top of the variable component with the
13 Align the top of the new DBText component
top of the DBText components.
with the top of the existing DBText components.
20 Select File | Save from the Delphi main menu. Lay Out the Group Footer Band for the
SubReport
1 Select the shape component in the group header
band.
Left 0.0
Top 0.0
Complete the Detail Band Layout for 3 Select the Item Total label in the group header
the SubReport band.
1 Place a shape component in the upper left corner
of the detail band. 4 Copy and paste the selection. Drag the new
label into the group footer band.
2 Configure the shape component:
5 Set the label caption to Total.
Left 0.0
Top 0.0 6 Select the List Price label in the group header
Width 6.25 band, then Shift-click the Total label. Click the
Height 0.2187 Right Align icon on the Align or Space toolbar.
Line Color Black
7 Select the shape in the group footer band, then
Fill Color None
Shift-click to select the Total label. Click the Align
3 Right-click over the shape and choose the Send Center icon on the Align or Space toolbar.
To Back menu option.
8 Select the vrItemTotal variable in the detail
4 Set the height of the detail band to 0.2083. band.
Note: Notice how the bottom of the shape extends 9 Copy and paste the selection. Drag the new
one screen pixel beyond the end of the detail band. variable into the group footer band.
This technique allows the shapes to overlap when
Note: This technique of copy/paste can be much
rendered on the page, creating the effect of a single
more efficient than creating a new component
line between detail bands.
because the DisplayFormat and Font proper values
are returned.
layout check
Master Detail Detail Report
REPORT TUTORIALS 311
10 Configure the variable: 5 Return to the Report Designer and select the
vrOrderTotal variable in the group footer band.
Name vrOrderTotal
Font Color White 6 Code the OnCalc event:
11 Use the Align or Space toolbar to Right Align Value := Value + vrItemTotal.Value;
the vrOrderTotal variable with the vrItemTotal
Note: This event handler retrieves the current total
variable.
for the item and adds it to the running total for the
12 Align the top the vrOrderTotal variable with the order. This OnCalc event will also fire once for
top of the Total label. each item record.
13 Select File | Save from the Delphi main menu. 7 Return to the Report Designer, right-click over
the vrOrderTotal variable, and select the Timing...
menu option.
layout check
Complete the Layout for SubReport1 7 Select Project | Compile rbMDDProj. Fix any
1 Click the 'SubReport1' tab. compilation problems.
2 Right-click over the Orderno DBText compo- 8 Select File | Save from the Delphi main menu.
nent located on the far left side of the detail band.
Note: The OverFlow property of the detail band
Set the ReprintOnOverFlow menu option to True.
will only be True when the orders for the current
Note: OverFlow occurs when the detail band runs customer do not fit on the page and therefore must
out of page space on the current page and must overflow onto an additional page. When this hap-
complete printing on the next page. For this report pens, the label will be visible.
we want to print the ItemNo followed by 'Contin-
Convert the Title Band to a Group
ued...' at the top of the page when the orders for a
Header Band
given customer overflow onto an additional page.
1 Select Report | Groups and create a group on
3 Place a label in the detail band and configure it: plOrder.CustNo. Uncheck the 'Keep group
together' option.
Caption Continued...
Name lblContinued 2 Set the height of the group header band to
Visible False 0.5208.
Font Name Times New Roman
3 Right click over the shape in the title band and
Font Size 10
set ParentHeight and ParentWidth to False.
Font Style Regular
Font Color Black 4 Select all of the components in the title band,
Text Alignment Left justified including the shape.
4 Select the SaleDate DBText component, then 5 Drag the selection into the group header band.
Shift-click the Continued label.
6 Select Report | Title from the Report Designer
5 Click the Align Top and Align Left main menu to remove the title band.
icons on the Align or Space toolbar.
Continued label:
lblContinued.Visible :=
ªppChildReport1.Detail.OverFlow;
7 Preview the completed report.
Master Detail Detail Report
REPORT TUTORIALS 313
Note: You should be able to get a general idea of
how things look. However, you will need to pre-
view the report at run-time to see the results of the
calculations and other event handlers.
Invoke the Report Designer and Note: By specifying the DrillDown option of the
Configure the Drill-Down subreport, we've associated the yellow shape with
1 Double-click on the Report component to dis- the report. Once we've done this, the subreport will
play he Report Designer. not print until the shape is clicked in the Print Pre-
view Window. The DrillDown... dialog sets the
2 Size and move the Report Designer window so
DrillDownComponent property of the SubReport.
that the Object Inspector is visible.
11 Select File | Save from the Delphi main menu.
3 Select the PageCount System Variable in the
footer band. Set the variable type to PageNoDesc.
layout check
Note: Drill-down reports should always be set to
one-pass. Otherwise, the entire report will be gen-
erated each time the user expands the subreport.
12 Preview the report. The items subreport should
5 Click the 'SubReport1' tab.
not appear. When you move the mouse over the
6 Place a shape in the left side of the detail band. yellow area, the cursor should change to a pointing
hand. When you click the yellow area, the subre-
7 Configure the shape:
port should appear. Clicking the same area again
Name shpClickMe should cause the subreport to disappear.
ParentWidth True
Top 0
Height 0.25
Fill Color Yellow
Line Color Yellow
Transfer the Customer List Report to 12 Set the Visible property of the label to False.
the Form
Note: This invisible label will not be used by the
1 Open the form containing the Customer List
report: it simply serves as a reminder of how these
report (rbCust.pas from “A Simple Report...”).
data access components are used. Whenever you
2 Double-click on the Report component to dis- have multiple sets of data access components on a
play the Report Designer. form, it is a good idea to label them. An alternate
way to accomplish this is to set the Tools | Environ-
3 Select File | Save As from the Report Designer
ment Options | Preferences | Show Component
main menu.
Captions option on, but this method requires that
4 Save the report template in the My RB Tutorials you space the components more widely than we
directory under the name CustList. find preferable.
Note: Saving a report layout to file is a quick and 13 Close the rbCust unit.
easy way to make the report more portable. Later
Transfer the Stock Summary Report to
in this tutorial we will open this saved layout in a
the Form
subreport. Layouts can also be loaded at run-time
1 Open the form containing the Stock Summary
using the Report.Template.LoadFromFile or Load-
report (rbStock.pas from the “Groups, Calcula-
FromDatabase method.
tions, ...” tutorial).
5 Close the Report Designer.
2 Double-click on the Report component to dis-
6 Select the data access components (tblCus- play the Report Designer.
tomer, dsCustomer, plCustomer).
3 Select File | Save As from the Report Designer
7 Copy the components into your clipboard. main menu.
8 Select View | Forms from the Delphi main 4 Save the report template in the My RB Tutorials
menu. Double-click on frmSectionSubreports to directory under the name StockSum.
make this form visible.
5 Close the Report Designer.
9 Paste the components onto this form.
6 Select the data access components (qryStock,
10 Place a standard Delphi label on the form, dsStock, plStock).
directly above these components.
7 Copy these components into your clipboard.
11 Set the label caption to 'Customer List Data'.
8 Select View | Forms from the Delphi main
menu. Double-click on frmSectionSub to make
this form visible.
321
Hooking Reports Together with Section-Style Subreports
REPORT TUTORIALS
9 Paste the components into the form and drag Create the Customer List SubReport
them to a position below the Customer List data 1 Place a SubReport component in the detail
access components. band.
10 Place a standard Delphi label on the form, 2 Position the subreport so that it is flush with the
directly above these components. top of the detail band.
11 Set the Caption to 'Stock Summary Data'. 3 Right-click over the subreport and select the
Section menu option.
12 Set the Visible property of the label to False.
Note: When a subreport is created, it defaults to a
13 Close the rbStock unit.
PrintBehavior of pbChild. Child subreports print
14 Select File | Save from the Delphi main menu. within the context of the parent band, much like a
stretching memo. Section subreports generate
Create and Configure the Main Report
entire pages, creating a whole section within the
1 Add a Report component to the form. parent report.
3 Double-click on the Report component to dis- Note: Whenever you set the name of a subreport,
play the Report Designer. the text in the subreport component and the text in
the tab at the bottom of the Report Designer is
4 Size and move the Report Designer window so
updated. The caption is also displayed in the
that the Object Inspector is visible.
Report Outline section of the Report Tree. When
5 Select Report | Header from the Report you have several subreports, it is a good idea to
Designer menu. The header band will be removed. name them so it is easier to keep track of them.
6 Select Report | Footer. The footer band will be
removed.
layout check
layout check
Hooking Reports Together with Section-Style Subreports
322 REPORT TUTORIALS
5 Click the 'srCustomerList' tab. 3 Right-click over the subreport and select the
Section menu option.
6 Select File | Load SubReport from the Report
Designer main menu and open the CustList.rtm 4 Name the subreport srStockSummary.
file. The Customer List report will appear in the
Note: We need to set the name of this subreport
Report Designer.
because we will be referring to this component by
name in an event handler later in the tutorial.
layout check
7 Click the Main tab at the bottom of the Report layout check
Designer to return to the layout of the main report. 5 Click the 'srStockSummary' tab.
8 Select File | Save from the Delphi main menu. 6 Select File | Load SubReport from the Report
Designer main menu and open the StockSum.rtm
Create the Stock Summary SubReport
file. The Stock Summary report will appear in the
1 Place a second SubReport component in the
Report Designer. Ignore any messages here
detail band.
regarding 'Invalid property values', as these are
2 Position it so that the top is flush with the bot- related to the event handlers formerly assigned to
tom of the Customer List subreport. the report.
ports via the Report Tree. You can also use the
Report Tree to change the layering.
323
Hooking Reports Together with Section-Style Subreports
REPORT TUTORIALS
7 Click the 'Main' tab at the bottom of the Report Copy the Event Handlers from the
Designer. Stock Summary Report
1 Re-open the form containing the Stock Sum-
8 Select File | Save from the Delphi main menu.
mary report (rbStock.pas).
Preview the Report at Run-Time
2 Locate the event handler declarations in the
1 Close the Report Designer.
form declaration at the top of the unit.
2 Select the Standard tab of the Delphi component
3 Copy the following event handler declarations
palette.
into your clipboard:
3 Add a Button component to the form.
procedure ppGroupHeaderBand1BeforeGenerate;
procedure ppDetailBand1BeforeGenerate;
4 Configure the Button component: procedure vrBuyTotalCalc;
procedure vrHoldTotalCalc;
Name btnPreview procedure vrSellTotalCalc;
Caption Preview
4 Locate the form class declaration at the top of
5 Put the following code in the OnClick event the rbSectSR unit.
handler of the button:
5 Paste the event handler declaration immediately
rbSectSub.Print; above the private section of the form class declara-
6 Select File | Save from the Delphi main menu. tion.
7 Run the Project. Note: You may have noticed that the Delphi Form
Designer automatically adds declarations to the
8 Click the Preview button. The report should be mysteriously unlabeled section at the top of your
displayed in the Print Preview form. The first three form class declaration. This is actually the pub-
pages should contain the Customer List report; the lished section of the form class. Declarations for
last thirty-nine pages should contain the Stock all of the event handlers and components within a
Summary report. form are placed in the published section in order to
Note: The calculations for the Stock Summary facilitate the streaming logic used to load and save
report are not correct, and the color-coding for this forms to dfm files. By pasting these declarations
report is gone. This is because we have not created into the published section of the form (and pasting
the event handlers for this report. We will com- the corresponding implementations in the unit), we
plete this task in the next section. make these event handlers assignable from the
Object Inspector.
Hooking Reports Together with Section-Style Subreports
324 REPORT TUTORIALS
6 Return to the rbStock unit and copy the 'FRec- 5 Click in the white space of the group header
ommendation' variable from the private section of band.
the form class declaration.
6 Select the Events tab of the Object Inspector.
7 Return to the rbSectSR unit and paste this vari-
7 Select the BeforeGenerate event, then expand
able into the private section of the form class decla-
the drop-down list of event handlers and select this
ration.
routine:
8 Return to the rbStock unit.
ppGroupHeaderBand1BeforeGenerate
9 Scroll down to the implementation section of
8 Select the AfterGenerate event to make sure the
the unit and copy all of the event handlers, save the
assignment was successful.
TfrmStockSummary.btnPreviewClick event.
9 Click in the white space of the detail band.
10 Return to the rbSectSR unit and paste the event
handlers in the implementation section of the unit. 10 Select the BeforeGenerate event, then expand
the drop-down list of event handlers and select this
11 Select File | Save from the Delphi main menu.
routine:
12 Return to the rbStock unit. Right-click over the
ppGroupHeaderBand1BeforeGenerate
code editor and select Close Page to close this unit.
11 Select the AfterGenerate event to make sure the
Re-attach the Event Handlers to the
assignment was successful.
Stock Summary Subreport
1 Scroll to the top of the rbSectSR unit, double- 12 Click in the white space of the group header
click the class name TfrmSectionSubreports, and band once again and double-click on the Before-
copy it into the clipboard. Generate event to activate the code editor. Change
the 'if' statement on the last line of the event han-
2 Scroll down to the implementation section and
dler to refer to srStockSummay instead of rbStock-
Replace the existing classname (TfrmStockSum-
Sum. The code should read:
mary) for each event handler with the new class
name (TfrmSectionSubreports). if srStockSummary.Report.Groups[0].FirstPage
then
3 Double-click on the rbSectSub report compo-
Note: The original event handler referred to the
nent to display the Report Designer.
rbStockSum report component. This event handler
4 Click on the srStockSummary tab at the bottom has to be changed to refer to the Report component
of the Report Designer. within the srStock subreport. A subreport compo-
nent actually consists of two components: the sub-
report component and the report component
contained within it. The subreport component is
used to position the subreport within the parent
report and to set various properties
325
Hooking Reports Together with Section-Style Subreports
REPORT TUTORIALS
related to print behavior. The report component is Add a Title Page to the Report
accessible via the Report property and contains the 1 Double-click on the rbSectSub report compo-
report itself. This component is no different than nent to display the Report Designer.
the report component you work with on a Delphi
2 Click the 'Main' tab.
form.
3 Select Report | Title from the Report Designer
13 Scroll down to the summary band and reconnect
main menu. A title band will be created.
the Variable components to their corresponding
OnCalc events: 4 Right-click over the title band and select the
Position... menu option.
Component Event
vrBuyTotal vrBuyTotalCalc 5 Set the height to 5.8125.
vrHoldTotal vrHoldTotalCalc
Begin Laying Out the Title Band
vrSellTotal vrSellTotalCalc
1 Place a label component in the upper left corner
Note: This tutorial illustrates how to reconnect the of the title band.
event handlers of the Stock Summary report so that
2 Configure the label:
you will better understand the situation. If we had
copied these event handlers into the SectSub unit Caption Title Page
before we loaded the Stock Summary report into Font Name Times New Roman
the subreport, the event handlers would be recon- Font Size 12
nected automatically by Delphi's object streaming Font Style Bold
logic. (You may recall that an error message stating Font Color Black
that the event handlers could not be found was dis- Text Alignment Left
played when we loaded the report layout.) It is 3 Place a label component near the middle of the
important to know that event handlers are recon- title band.
nected based on their procedure name. When you
want event handlers to reconnect automatically, 4 Configure the label:
they must have the same names as those saved in Caption Marine Adventures &
the report layout. Sunken Treasures Co.
14 Select File | Save from the Delphi main menu. Font Name Times New Roman
15 Run the Project. The Stock Summary report Font Size 20
should now be color-coded and the totals should Font Style Bold & Italic
calculate properly. Text Alignment Center
Left 1.3542
Top 1.9166
Hooking Reports Together with Section-Style Subreports
326 REPORT TUTORIALS
5 Place a label component just below the previous 10 Configure the label:
label.
Caption Arthur Andreesen &
6 Configure the label: Co.
Caption Prepared By
Font Name Times New Roman
Font Size 14
Complete the Title Band Layout
Font Style Bold & Italic 1 Place a label component just below the previous
Text Alignment Center label.
Left 3.4896
Top 2.75 2 Configure the label:
9 Place a label component just below the previous Caption Table of Contents
label. Font Name Times New Roman
Font Size 20
Font Style Bold & Italic
Text Alignment Center
Left 2.9375
Top 3.8646
6 Select the Layout tab. Enter the following val- 3 Select Report | Header from the Report
ues: Designer main menu. The header band will be
removed from the report.
Columns 4
Column Width 1.75 4 Select Report | Footer from the Report Designer
Column Position 1 0.28 main menu. The footer band will be removed from
Column Position 2 2.34 the report.
Column Position 3 4.4 5 Place a shape in the detail band.
Column Position 4 6.46
6 Configure the shape:
7 Select the Margins tab. Enter the following val-
ParentHeight True
ues:
ParentWidth True
Top 0.4
7 Select File | Save from the Delphi main menu.
Bottom 0.49
Left 0.2969
Right 0.2969
layout check
8 Preview the report. You should see four col- band. It is fairly common for the alignment shape
umns of shapes. Print this page to the printer. to be off a little, even though the exact measure-
ments are sent to the printer. This is usually due to
The labels should look like this when you preview:
variation in the label sheets and to the calibration
of the printer being used. Generally, you must
tweak the report layout until the alignment shape
appears in the correct location, then set the Visible
property of the shape to False and use the template
like any other report.
9 Take the sheet just printed and place it behind an 6 Set the ParentHeight and ParentWidth of the
Avery 5267 Laser label sheet. Hold the sheets up shape to True.
to a bright light so you can see exactly where the 7 Click the Select Report icon and use the Object
lines fall on the labels. Ideally, the edges of the Inspector to set AutoStop to False and PageLimit
lines should match up with the edges of the labels. to 1.
Note: By placing a shape in the detail band, we
can see exactly where the label information will
print. If the shape does not match up with the
labels, we can make adjustments to the margins,
column positions, and row spacing of the detail
Using Columns to Create Mailing Labels
332 REPORT TUTORIALS
9 Preview.
Create a New Application 9 Right-click over the project name once again
Note: This tutorial builds upon the 'Creating a and select the Save menu option.
Report via the Report Wizard' tutorial. You can
10 Save the project under the name rbTTProj in the
either complete this tutorial or use the rbViaWiz
My RB Tutorials directory.
form located in the RBuilder\Tutorials directory.
Note: Save your work frequently to avoid losing
1 Select File | New Application from the Delphi
changes should your computer unexpectedly lose
menu. This will create a new project and a blank
power or crash.
form.
Complete the Report Wizard Tutorial
2 Close the new form and unit without saving.
1 Rename the Report component rbPrintData.
3 Select File | Open from the Delphi main menu.
2 Delete the Preview button from the form.
Locate the rbViaWiz unit in the Tutorials directory
and open it. Load the Tabular Style Report Template
1 Double-click on the Report component to dis-
4 Set the Form name to 'frmPrintToTextFile'.
play the Report Designer.
5 Select File | Save As from the Delphi menu and
2 Select File | Open from the Report Designer
save the form under the name rbToTxt in the My
main menu.
RB Tutorials directory (established on page 181).
3 Open the CustTab.rtm file.
Note: It is important to name the form and save the
form's unit using the names given above because
the form will be used in later tutorials.
Assign User Names to the DBText 6 Use the arrows to the right of the Available Con-
Components trols list box to move each of the DBtext compo-
1 Set the UserName for each of the DBText com- nents to the Selected Controls list box in the
ponents based on the field to which they are following order:
assigned. Use the Object Inspector to assign the
Company
following UserNames:
CustNo
dbtCompany Contact
dbtCustNo Phone
dbtContact Fax
dbtPhone City
dbtFax State
dbtCity Country
dbtState
7 Click the OK button to close the dialog.
dbtCountry
Configure the Report to Print to File
Specify the File Name and Format
1 Click the Select Report icon located at the upper
1 Select File | Print to File Setup from the Report
left corner of the Report Designer workspace
Designer main menu. The Print to File Setup dia-
where the horizontal and vertical rulers meet.
log will be displayed.
2 Set the Report's AllowPrintToFile property to
2 Click the File button.
True in the Object Inspector.
3 Access the My RB Tutorials directory and enter
3 Set the Report's DeviceType to TextFile.
customer as the file name. Click the Save button to
close the file dialog. 4 Select File | Save As from the Report Designer
menu and save the modifications to CustTab.rtm.
4 Select Tab Delimited from the File Type drop-
down list. Soft Code the Template Name
1 Close the Report Designer.
5 Select the detail band in the Bands list. The
Available Controls list will display the components 2 Access the Delphi Code Editor.
residing in the detail band.
3 Search the unit for all occurrences of 'rbCusto-
merList' and change them to 'rbPrintData.'
335
Printing to a Text File
REPORT TUTORIALS
Soft Code the Text File Name 7 Select the Vertical style report and click the
1 Access the OnClick event for the Print button Print Button. Notice that there are not any Print to
and change the event handler so that it looks like File options in the dialog.
the code below.
8 Close the dialog and the form.
2 Select Project | Compile rbTTProj. Fix any
The print dialog should look like this:
compilation problems.
Tabular Report Print Dialog with Print to File Option
3 Select File | Save from the Delphi main menu.
• Print a report from data stored in a text file Create the Text DataPipeline Component
1 Select the RBuilder tab of the Delphi compo-
Create a New Application
nent palette.
Note: This tutorial uses the Customer.txt file cre-
ated in the previous tutorial. You can either com- 2 Place a TextPipeline component on the form.
plete this tutorial or use the Customer.txt file
3 Configure the TextPipeline component:
located in the RBuilder\Tutorials directory.
FileName Customer.txt
1 Select File | New Application from the Delphi
FileType ftTab
menu. This will create a new project and a blank
Name plCustomer
form.
Define the Data Fields for the Text
2 Set the Form name to 'frmPrintFromTextFile'.
Pipeline
3 Select File | Save As from the Delphi menu and 1 Double-click on the TextPipeline component to
save the form under the name rbFrmTxt in the My display the Fields Editor.
RB Tutorials directory.
2 Add a new field by clicking the Add button.
Note: It is important to name the form and save the
3 Set the following properties for the field:
form's unit using the names given above because
the report will be used in later tutorials. FieldName Company
FieldLength 30
4 Select View | Project Manager from the Delphi
main menu.
Note: The TextPipeline enables ReportBuilder to 3 Use the two drop down lists at the upper left
use data from a text file as if it were stored in a corner of the Report Designer to set the DataPipe-
database. The field lengths specified here are max- line and DataField properties:
imum lengths. For example, the actual company
DataPipeline plCustomer
names stored in the file may vary in length, but
DataField Company
none may exceed 30 characters.
Note: The report and Report Designer behave in
4 Add the following fields:
the same manner whether the report is connected to
FieldName FieldLength a DBPipeline, a TextPipeline, or any other type of
CustNo 10 pipeline, including a custom data pipeline descen-
Contact 20 dant that you or another developer has created.
Phone 15
4 Preview the report. The Company field should
FAX 15
be listed.
City 15
State 20 5 Select the Design tab to return to the design
Country 20 workspace.
5 Close the Fields Editor. Load the Vertical Style Report Template
1 Select the File | Open... from the Report
6 Select File | Save from the Delphi main menu.
Designer main menu.
Create a Report and Connect it to the
2 Open the CustVert.rtm file.
Data
Note: The CustVert.rtm file was created in the
1 Add a Report component to the form. Report Wizard tutorial. The report was connected
2 Configure the Report component: to a DBPipeline named plCustomer. We now have
a text pipeline named plCustomer whose fields we
DataPipeline plCustomer
have defined with the same names as the fields
Name rbCustomerList
used from the Customer.db table. When the
Test the Data Connection CustVert.rtm report is loaded, the data is automati-
1 Double-click on the Report component to dis- cally reconnected because the pipeline and field
play the Report Designer. names are identical.
2 Place a DBText component in the detail band 3 Select File | Save from the Delphi main menu.
and set it to AutoSize.
4 Select the Preview tab to view the report.
Soft Code the Text File Name 8 Click on the Preview button. The report should
1 Add the following code to the OnCreate event be displayed in the Print Preview form:
of the form:
procedure
ªfrmPrintFromTextFile.FormCreate(Sender:
ªTObject);
begin
plCustomer.FileName :=
ªExtractFilePath(ParamStr(0)) +
ª'Customer.txt';
end;
Name btnPreview
Caption Preview
10 Save the project under the name rbFJProj in the 2 Copy the PipeDataToGrid routine from form
My RB Tutorials directory. dm0139 in the RBuilder\Demos\1. Reports direc-
tory.
Note: Save your work frequently to avoid losing
changes should your computer unexpectedly lose 3 Paste the code at the bottom of the implementa-
power or crash. tion section of the rbFrmJIT unit.
Note: This code assigns the text file name (assum- 4 Repeat steps 2 and 3 to add the following fields:
ing the text file is in the same directory as the
FieldName FieldLength
application) and populates the string grid with data.
CustNo 10
5 Select Project | Compile rbFJProj. Fix any com- Contact 20
pilation problems. Phone 15
FAX 15
6 Select File | Save from the Delphi main menu.
City 15
7 Run the project. The customer data should be State 20
displayed in the grid. Country 20
Note: This routine returns the data field value for 8 Click on the Preview button.
the current record. The field names are stored in
the first row of the grid and are used to determine
the column number of the given field name. This
column number and current row index are used to
retrieve the current field value.
• Edit the standard Rich Text component 3 Select File | Save As from the Delphi menu and
save the form under the name rbMailM in the My
• Use the mail/merge feature
RB Tutorials directory.
DatabaseName DBDEMOS
Name tblClient
TableName clients.dbf
Using the Rich Text Component for Mail/Merge
346 REPORT TUTORIALS
2 Size and move the Report Designer window so Note: We've positioned the RichText control so
that the Object Inspector is visible. that it fills the entire detail band. This allows us to
use the margins of the report to control the posi-
3 Select File | Page Setup from the Report
tioning of the letter, as opposed to positioning the
Designer main menu.
RichText component within the band. The height
4 Select the Margins tab. of 4 is arbitrary: it will simply allow us to read the
entire contents of the letter while designing. When Add Fields to the Letter
the report prints, the RichText component will cal- 1 Select Edit | Insert Field. A list of fields from
culate its height based on the length of the letter. the client table will be displayed.
4 Locate the MMLetter.RTF file in the 13 Locate the start of the second paragraph (starts
RBuilder\Tutorials directory. Open this file. with the words 'We would like...').
layout check
Using the Rich Text Component for Mail/Merge
348 REPORT TUTORIALS
15 Close the Rich Text Editor. Click the Yes button 9 Click the Preview button. The report should be
when the Save Changes dialog appears. five pages, with one letter per page.
Name btnPreview
Caption Preview
Creating a Crosstab
• Summarize data in a grid format 1 Select File | New Application from the Delphi
menu. This will create a new project and a blank
• Create a crosstab report
form.
DataSourcedsOrder
Name plOrder
Create a Report
Name rbOrder
diagram check
cell. When the indicators appear, release the
mouse button.
8 Click OK.
diagram check
7 Set it to PageSetDesc.
RAP TUTORIALS
RAP TUTORIALS
Concatenating Fields
Create a DataView
1 In the open Report Designer, click the Data tab.
layout check
2 Add two DBText controls to the Detail
band.
3 Click on DBText1 and use the Data Field drop 6 Select all of the components by shift-clicking,
down list to select First Name. and select the Align Top icon on the Align or
Space Toolbar.
layout check
3 Click Variable1.
Add the Concatenation Code 1 Click on the First Name entry in the Toolbox
The Data tab of the Code Toolbox should be and drag it to the Code Editor, just to the right of
active, if it is not, select it. In the upper window of the "Value := " line.
the Code Toolbox, you should see the pipeline we
2 Drag the Last Name entry to the right of the line
have added, plClients. Below that, you should see
of code.
an entry for each field in the pipeline. These items
are draggable. 3 Type in the remaining characters of the line as
shown below.
We’re going to enter the following line of code, but
we are going to construct it via drag and drop.
end;
Concatenating Fields
358 RAP TUTORIALS
2 To view the results, click the Preview tab. 2 Navigate to the My RAP Tutorials folder and
save the report as RAP Tutor 1.rtm.
Color-Coding Components
• Use RAP at run-time 2 Enable RAP by removing the “x” from in front
of $DEFINE RAP in the MyEurpt.pas interface.
• Add local variables
3 Compile and run the demo project.
• Add event handler code to color-code a compo-
nent. 4 Select the Customers folder.
Enable DetailBeforePrint
1 Click the Calc tab to activate the Calc work-
space.
procedure DetailBeforePrint;
var
lsString: String;
liLength: Integer;
begin
lsString := plCustomer[‘Company’];
liLength := Length(lsString);
Delete(lsString, 2, liLength -1);
else
ppCustomerListDBText2.Color := clWhite;
end;
361
Color-Coding Components
RAP TUTORIALS
Dynamic Duplexing
• Use duplexing to print a disclaimer on the back 2 Enable RAP by removing the “x” in front of
of every page of a report. $DEFINE in the MyEUrpt.pas interface.
• Print the data only on even numbered pages and 3 Build and run the demo project.
the disclaimer on the odd numbered pages.
4 Navigate to the folder of your choice and click
the New Report button. The Report Designer will
open automatically.
Create Report Layout Note: The group header will work for every page
1 Click the Design tab to begin laying out the but the last one. Since the data will always end on
report. an odd numbered page, we’ll need to arrange
something to print the disclaimer on the back of the
2 Turn off the Header and Footer bands by select-
last page.
ing those items in the Report Menu.
12 Position the Company DBText component:
3 Select Report | Groups to display the Groups
dialog. Left 0.0313
Top 0.0208
4 Select Customer.CustNo from the Groups drop
down list and click Add to create the group. 13 Position the OrderNo DBText component:
end;
365
Dynamic Duplexing
RAP TUTORIALS
• Add two functions and a category to the func- 2 Select File | New | Unit from the Delphi menu.
tions list in the Code Toolbox.
3 Select File | Save As | c:\ My RAP Tutorials
• Add a pass-through function to retrieve the appli-
4 Save the file as myRapFuncs.pas. This unit will
cation’s filename, a function to expose the
contain our new pass-through functions. This unit
ExtractFilename Delphi function, and a category
will contain our new pass-through functions.
named “Filename.”
Edit Uses Clause
1 Add a uses clause between the interface and
implementation sections.
unit myRapFuncs;
interface
uses
Forms, raFunc, ppRTTI;
implementation
type
TmyFilenameFunction = class(TraSystemFunction)
public
class function Category: String; override;
end;
implementation
result := 'Filename';
end;
end;
Implement ExecuteFunction
In the unit's implementation section, enter the fol-
lowing:
begin
lsResult := Application.Exename;
SetParamValue(0, lsResult);
end;
Implement GetSignature
In the unit's implementation section, enter the fol-
lowing:
end;
Adding Functions to RAP
370 RAP TUTORIALS
Implement HasParams
In the unit's implementation section, enter the fol-
lowing:
result := False;
end;
Add Initialization
1 At the bottom of the unit, before the final end,
add an initialization section.
initialization
raRegisterFunction('ApplicationFilename',TmyApplicationFilenameFunction);
end.
1 Open the RBuilder | Demos| 3. EndUser | 2 Click the Language tab in the Code Toolbox and
1. Report Explorer | EndUser.dpr project. scroll to the top of the Toolbox treeview to find the
Function node.
2 Open the main form, myEURpt.pas.
3 Click the Filename node.
3 Scroll down until you see a series of
{$DEFINE} statements. Look for the one that In the function list you should see the fruits of your
defines RAP and remove the 'x' from in front of the efforts.
$DEFINE.
Add ApplicationFilename to Code 4 Add the code for the ReportBeforePrint event.
1 Right-click on the Report Explorer's tree view
5 Right-click on the Code Editor and select Com-
and select Events.
pile.
2 Select the Report node, if it is not already
6 Assuming the code compiles, click the Preview
selected, and click the BeforePrint event listed in
tab.
the right-hand pane.
Congratulations! You should see a message dialog
3 Click the Code Editor to activate the event han-
with the application's filename.
dler stub and add a local variable as shown below.
lString := ApplicationFilename;
ShowMessage(lString);
end;
373
Extending the RAP RTTI
RAP TUTORIALS
• Make RAP aware of a new component. 2 Select File | New | Unit, to create a new unit.
• Register a new class to surface TDataBase within 3 Save the unit as myRapClass.pas in the C: | My
RAP. RAP Tutorials directory. This unit will contain our
new TraRTTI descendant.
• Add support for the public property, Directory
and the public method, ValidateName. 4 In the new unit, add a uses clause between the
interface and implementation sections and add
Classes, Forms, raFunc, ppRTTI, db, dbTables and
ppUtils to the clause.
unit myRapClass;
interface
uses
Classes, Forms, raFunc, ppRTTI, db, dbTa-
bles, ppUtils
Extending the RAP RTTI
374 RAP TUTORIALS
Declare TmyTDataBaseRTTI
Next, we must find the proper TraRTTI descendant
from which to descend this class. TDataBase
descends from TCustomConnection which
descends from TComponent. There is no TraRTTI
descendant for TCustomConnection, but there is
one for TComponent (TraTComponentRTTI) so
we'll use that one.
TmyTDataBaseRTTI = class(TraTComponentRTTI)
public
class procedure GetPropList(aClass: TClass; aPropList: TraPropList); override;
class function RefClass: TClass; override;
class function GetPropRec(aClass: TClass; const aPropName: String; var aPropRec:
TraPropRec): Boolean; override;
class function CallMethod(aObject: TObject; const aMethodName: String; aParams:
TraParamList; aGet: Boolean): Boolean; override;
class function GetParams(const aMethodName: String): TraParamList; override;
class function GetPropValue(aObject: TObject; const aPropName: String; var
aValue): Boolean; override;
class function SetPropValue(aObject: TObject; const aPropName: String; var
aValue): Boolean; override;
end;
Implement GetPropList
Implement the overridden method, GetPropList
with the following code:
aPropList.AddProp('Directory');
aPropList.AddMethod('ValidateName');
end;
375
Extending the RAP RTTI
RAP TUTORIALS
Implement RefClass
Add the following code to the implementation sec-
tion:
Result := TDataBase;
end;
Implement GetPropRec
Implement the overridden method, GetPropList
with the following code:
Result := True;
if ppEqual(aPropName, 'Directory') then
PropToRec(aPropName, daString, False, aPropRec)
else if ppEqual(aPropName, 'ValidateName') then
MethodToRec(aPropName, True, aPropRec)
else
Result := inherited GetPropRec(aClass, aPropName, aPropRec);
end;
Extending the RAP RTTI
376 RAP TUTORIALS
Implement CallMethod
Implement the overridden method, CallMethod,
with the following code:
Result := True;
lDataBase := TDataBase(aObject);
if ppEqual(aMethodName, 'ValidateName') then
begin
aParams.GetParamValue(0, lsName);
try
lDataBase.ValidateName(lsName);
lbResult := True;
except
On EDatabaseError do
lbResult := False;
end;
aParams.SetParamValue(1, lbResult);
end
else
Result := inherited CallMethod(aObject, aMethodName, aParams, aGet);
end;
Implement GetParams
Implement the overridden method, GetParams,
with the following code:
end;
377
Extending the RAP RTTI
RAP TUTORIALS
Implement GetPropValue
Implement the overridden method, GetPropValue,
with the following code:
Result := True;
if ppEqual(aPropName, 'Directory') then
String(aValue) := TDataBase(aObject).Directory
else
Result := inherited GetPropValue(aObject, aPropName, aValue);
end;
Implement SetPropValue
Implement the overridden method, SetPropValue,
with the following code:
Result := True;
if ppEqual(aPropName, 'Directory') then
TDataBase(aObject).Directory := String(aValue)
else
Result := inherited SetPropValue(aObject, aPropName, aValue);
end;
Code TmyDevelopersFunction
type
end;
implementation
Result := 'Developer';
end;
379
Extending the RAP RTTI
RAP TUTORIALS
Code TmyGetDelphiComponentFunction
implementation
GetParamValue(0, lsString);
lResult := Application.MainForm.FindComponent(lsString);
SetParamValue(1, lResult);
end;
end;
2 Right-click the Code Explorer treeview and 8 Right-click the Code Explorer treeview and
select Module. select Events.
3 Select the Declarations node, right-click the 9 Select Variable1 in the treeview.
Variables item and select New.
10 Right-click the OnCalc event and select New.
4 Enter the following into the Code Editor:
11 Enter the following code in the event handler:
gDataBase: TDataBase;
Value := gDataBase.Directory;
gbValidName: Boolean;
12 Select Variable2 in the treeview.
5 Now select the Events node, right-click OnCre-
ate and select New. 13 Right-click the OnCalc event and select New.
6 In the event handler, enter the code for the Glo- 14 Enter the following code in the event handler:
bal OnCreate event. if gbValidName then
Value := 'True'
else
Value := 'False';
gDataBase := TDataBase(GetDelphiComponent('euDatabase'));
if (gDataBase <> nil) then
begin
gbValidName := gDataBase.ValidateName('DBDEMOS');
end;
Extending the RAP RTTI
382 RAP TUTORIALS
layout check
5 For this criteria, set Operator to "Like" and set
Value to "J."
7 Right-click the second criteria and select "Insert Write the Code
OR". 1 Click the Calc tab.
8 Click the OK button in the Query Designer. 2 Right-click the Code Explorer's treeview and
You should now see the DataView. select Events.
9 Click the Preview button on the DataView. You 3 Click the Report node.
should see two records displayed, Jennifer Davis 4 Right-click the OnStartPage event in the list-
and Arthur Jones. view and select New.
Layout the Report 5 In the event handler stub in the Code Editor,
1 Click the Design tab. enter the following code (note that you can either
2 Turn off the Footer band by selecting Footer type this in or drag and drop the code from the
from the Report menu. Code Toolbox):
Report.GetAutoSearchDescription-
3 Drop two DBText controls onto the Detail Lines(Memo1.Lines);
band.
Name pgCtlMain
Height 141
Align alTop
Style tsFlatButtons
Name bnOK
Left 110
Top 148
Caption 'OK'
Default True
ModalResult mrOK
Displaying Delphi Forms from RAP
388 RAP TUTORIALS
3 Place another Button on the form and set its 7 Now, place a RadioGroup on tabStartup and set
properties: its properties:
tabMasterRecord.TabVisible := False;
if aStartupPage then
pgCtlMain.ActivePage := tabStartup
else
pgCtlMain.ActivePage := tabMasterRecord;
ebHeading.Text := aDefaultHeading;
lblCompanyName.Caption := aCompanyName;
end;
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, raFunc,
ppRTTI, myUserInputForm;
end;
Displaying Delphi Forms from RAP
390 RAP TUTORIALS
end;
TmyShowStartupFormFunction = class(TmyUserInputFormFunction)
procedure ExecuteFunction(aParams: TraParamList); override;
class function GetSignature: String; override;
end;
391
Displaying Delphi Forms from RAP
RAP TUTORIALS
6 Implement TmyShowStartupFormFunction
with this code.
GetParamValue(0, lString);
GetParamValue(1, lInteger);
lInputForm := TfrmMyUserInput.Create(Application);
try
lInputForm.InitDialog(True, lString, '');
lInteger := lInputForm.rgDestination.ItemIndex;
lbResult := True;
end
else
lbResult := False;
finally
lInputForm.Free;
end;
SetParamValue(0, lString);
SetParamValue(1, lInteger);
SetParamValue(2, lbResult);
end;
end;
TmyShowMasterRecordFormFunction = class(TmyUserInputFormFunction)
procedure ExecuteFunction(aParams: TraParamList); override;
class function GetSignature: String; override;
end;
Displaying Delphi Forms from RAP
392 RAP TUTORIALS
8 Implement TmyShowMasterRecordFormFunc-
tion with this code.
lInputForm := TfrmMyUserInput.Create(Application);
try
lInputForm.InitDialog(False, '', lString);
lInputForm.cbIncludeAddress.Checked := lBoolean;
begin
lBoolean := lInputForm.cbIncludeAddress.Checked;
lbResult := True;
end
else
lbResult := False;
finally
lInputForm.Free;
end;
SetParamValue(1, lBoolean);
SetParamValue(2, lbResult);
end;
end;
initialization
raRegisterFunction('ExecuteStartupForm', TmyShowStartupFormFunction);
raRegisterFunction('ExecuteMasterRecordForm', TmyShowMasterRecordFormFunction);
393
Displaying Delphi Forms from RAP
RAP TUTORIALS
Add Units to Project 6 The two variables inside the region will hold
1 Open the RBuilder | Demos | 3. EndUser | address information so place the region and the
1. Report Explorer | EndUser.dpr project. variables beneath the DBText component.
2 Select Project | Add to project, and add the two 7 Turn off the line around the region.
new units, myUserInputForm.pas and myRapFunc-
sForm.pas. 8 In the Title of the report, add 3 Variables .
3 Compile and run the project. 9 Variable3 will be the Report title. Center it at
the top of the band and set it to 16pt Arial.
4 Create a new report.
10 Variable4 will be our salutation. Place it half an
Create a DataView inch below Variable3 against the left margin. Set it
1 Once the Report Designer is open, click the to 10pt Times New Roman.
Data tab.
11 Variable5 is the message body. Place it just
2 Select File | New | Query Designer and click below Variable 4 against the left margin. Set its
OK. width to 7.5" and its height to 0.5". Set WordWrap
3 In the Query Designer Tables tab double-click to True.
the Customer table.
12 In the Detail band, add 3 DBText controls.
4 Double-click the Orders table to open the Join
Table dialog and remove the TaxRate join from the 13 Place the DBText controls left to right, assigned
Joined Fields list. Then click OK. to OrderNo, SaleDate and AmountPaid.
5 In the Fields tab check the All Fields check box. 14 Set the Detail band to Static height and set its
height to 0.25".
6 Click OK to create the DataView.
Declare Global Variables
Layout the Report 1 Click the Calc tab.
1 Click the Design tab
2 Right-click the Code Explorer's treeview and
2 From the Report menu, select Groups... and cre- select Module.
ate a group based on plCustomer.CustNo
3 Select the Declarations node.
3 From the Report menu, select the Title, Header
and Footer items to turn on the Title band and turn 4 Right-click the Variables item in the listview
off the Header and Footer bands. and select New.
Implement Global OnCreate 4 Enter the code on the following page for the
1 Click the Events node. event handler.
2 Right click the OnCreate item in the listview Basically, in this code we are executing the startup
and select New. version of the form where we ask for a report head-
ing and for a recipient. liIndex tells us which radio
3 In the Code Editor, add the following two local
button was selected on the form, so we carefully
variables to the event handler:
phrase our salutation accordingly.
var
liIndex: Integer;
lbExecuted: Boolean;
begin
liIndex := 0;
myHeaderString := 'Monthly Sales Report';
end;
395
Displaying Delphi Forms from RAP
RAP TUTORIALS
var
lDisplayAddress: Boolean;
begin
lDisplayAddress := True;
ExecuteMasterRecordForm(plCustomer['Company'], lDisplayAddress);
Region1.Visible := lDisplayAddress;
end;
Displaying Delphi Forms from RAP
396 RAP TUTORIALS
Variable3:
Value := MyHeaderString;
Variable4:
Value := MyRecipientString;
Variable5:
Value := MyDescriptionString;
Variable1:
Variable2:
APPLICATION TUTORIALS
APPLICATION TUTORIALS
Building a Reporting Application
• Use your own customized print preview form 3 Select File | Save As from the Delphi menu and
save the form under the name rbMain in the My
RB Tutorials directory (established on page 181).
tory. If you have not completed this tutorial, you TrbReportForm = class(TForm)
protected
can find this unit in RBuilder\Tutorials. Add this function GetReport: TppReport; virtual;
form to your project. ªabstract;
public
property Report: TppReport read
ªGetReport;
end;
403
Building a Reporting Application
APPLICATION TUTORIALS
Note: A Delphi form is just another class within Note: We must add the rbClass unit to the uses
the VCL. This declaration creates a non-visual clause so that we can descend from the TrbReport-
descendant of a TForm. It then declares a report Form.
property that can be used by any routine referenc-
5 Change the inherited form name from TForm to
ing the class. Next we will modify a visual form to
TrbReportForm. The first line of the form class
become a descendant of TrbReportForm. We will
declaration should look like this:
then implement the GetReport procedure by return-
ing the report object contained in the form. This type
TfrmViaReportWizard =
technique allows us to easily work with the report ªclass(TrbReportForm)
objects in TrbReportForm descendants.
6 Click on the rbClass tab in the Code Editor.
5 Select File | Save from the Delphi main menu.
7 Copy the protected section of the class (includ-
Make the Tutorial Report Form a ing the protected keyword) into your clipboard.
Descendant of TrbReportForm Here is the code you need to copy:
1 Select View | Project Manager from the Delphi protected
main menu. function GetReport: TppReport; virtual;
ªabstract;
2 Double-click on the rbViaWiz unit to open the
8 Click on the rbViaWiz tab in the Code Editor.
form.
9 Scroll down until you locate the public keyword
3 Access the rbViaWiz unit and maximize the
at the bottom of class declaration for the form.
Code Editor.
10 Insert the contents of your clipboard above the
4 Add rbClass to the uses clause at the top of the
public keyword. The declaration should now look
unit. The code should look like this:
like this:
unit rbViaWiz;
protected
interface function GetReport: TppReport; vir-
tual;
uses ªabstract;
Windows, Messages, SysUtils, Classes, public
Graphics, Controls, Forms, Dialogs, { Public declarations }
StdCtrls, ppBands, ppCtrls, ppPrnabl,
ppClass, ppDB, ppProd, ppReport, end;
ppComm, ppCache, ppDBPipe, ppDBBDE, Db,
DBTables, ppVar, rbClass;
Building a Reporting Application
404 APPLICATION TUTORIALS
11 Replace the virtual and abstract keywords with 4 Double-click the OnCreate event. The event
override so the declaration looks like this: handler shell will be generated and the Code Editor
will be displayed.
protected
function GetReport: TppReport;
ªoverride; 5 Add the following line of code to the event han-
public dler:
{ Public declarations }
end; lbxReports.Items.AddObject('Creating a
ªReport via the Report Wizard',
12 Copy the GetReport function declaration into ªTObject(TfrmViaReportWizard));
the clipboard and scroll down to the implementa-
Note: This code stores a description of the report
tion section of the unit.
and the class type for the form containing the
13 Paste the declaration into the implementation report in the list. The class type will be used to
section, remove the override keyword, and add the instantiate an instance of the form.
following code so that the function looks like this:
Code the LaunchReport Procedure in
implementation the Main Form
{$R *.DFM}
1 Add the LaunchReport procedure declaration to
function TfrmViaReportWizard.GetReport: the private section of the main form. The code
ªTppReport;
begin should look like this:
Result := rbCustomerList;
end; private
procedure LaunchReport;
Note: This routine will be called whenever the public
rbReportForm.Report property is referenced. { Public declarations }
end;
14 Select File | Save from the Delphi main menu. 2 Add the following units to the uses clause at the
15 Close the Code Editor. top of the unit:
ppReport, rbViaWiz, rbClass
Populate the List Box in the OnCreate
Event of the Main Form
1 Select View | Project Manager from the Delphi
main menu.
3 Add the LaunchReport procedure to the imple- 2 Select the ListBox control and then double-click
mentation section. The code should look like the on the OnDblClick event in the Object Inspector.
code below.
3 Add a call to LaunchReport to this event han-
4 Select File | Save from the Delphi main menu. dler. The code should look like this:
Note: This routine retrieves the class type from the procedureTfrmMain.lbxReportsDlClick(Sender:
ªTObject);
list box, instantiates a form of that type, retrieves begin
the report from the form, and then prints the report. LaunchReport;
end;
This routine assumes two things: that the
Report.ModalPreview property is True and that the 4 Select the Preview button on the form and then
class type in the ListBox is a TrbReportForm double-click on the OnClick event in the Object
descendant. As you can see, the abstract TrbRe- Inspector.
portForm class comes in quite handy. As we go 5 Add a call to LaunchReport to this event han-
forward adding more reports to this project, we can dler.
make the forms descendants of this class and add
6 Select File | Save from the Delphi main menu.
the description and class type to the list box, and
the reports will work ’automatically’. 7 Select Project | Compile rbMain. Fix any com-
pilation problems.
Hook the LaunchReport Procedure to
the ListBox and Preview Button 8 Close the Code Editor and the rbMain form.
1 Click the Toggle Form/Unit icon on the Delphi
View toolbar (or hit the F12 key). You should see
the main form.
procedure TfrmMain.LaunchReport;
var
lFormClass: TFormClass;
liIndex: Integer;
lForm: TForm;
lReport: TppReport;
begin
liIndex := lbxReports.ItemIndex;
if (liIndex = -1) then Exit;
lFormClass := TFormClass(lbxReports.Items.Objects[liIndex]);
lForm := lFormClass.Create(Application);
lReport := TrbReportForm(lForm).Report;
lReport.Print;
lForm.Free;
end;
Building a Reporting Application
406 APPLICATION TUTORIALS
9 Run the application. The list box should contain Note: This register call replaces the built-in
one item. If you double-click on the item or select ReportBuilder Print Preview form with this custom
the item and click the Preview button, you should version. The initialization section fires when the
see the report in the Print Preview window. unit is loaded. The unit is loaded only if it appears
in the uses clause of another unit or is included in
Create a Customized Print Preview
the project. For this reason, you should always add
Form
your preview form to your project or add the form's
1 Close the application and return to the Delphi
unit name to the uses clause of your application's
development environment.
main unit.
2 Select File | Open from the Delphi main menu.
8 Select File | Save from the Delphi main menu.
Locate the ppPrvDlg unit in the RBuilder\Source
directory. Open this unit. 9 Close the Code Editor.
3 In the Object Inspector, change the form name Add the Customized Print Preview
from ppPrintPreview to rbPrintPreview. (You may Form to your Project
have to use the drop-down list box at the top of the 1 Select the View | Project Manager option from
Object Inspector to find the ppPrintPreview form). the Delphi main menu.
4 Save the form in the My RB Tutorials directory 2 Right-click over rbMainProj and select the
under the name rbPrvDlg. Add... menu option.
5 Select the panel at the top of the form (named 3 Locate rbPrvDlg.pas in the My RB Tutorials
pnlPreviewBar). directory and add it to the project.
6 Set the color to clAqua. 4 Right-click over rbMainProj and select the
Options... menu item.
7 Bring the Code Editor to the front and scroll to
the very bottom of the unit and check the initializa- 5 Select the Forms tab and move the rbPrintPre-
tion section of the unit. The code should look like view form from the Auto-create list to the Avail-
this: able forms list.
initialization 6 Select Project | Compile rbMainProj. Fix any
ppRegisterForm(TppCustomPreviewer, compilation problems.
ªTrbPrintPreview);
finalization
ppUnRegisterForm(TppCustomPreviewer);
end.
407
Building a Reporting Application
APPLICATION TUTORIALS
• Combine ReportBuilder components into an end- 2 Select File | Working Directory from the Data-
user reporting solution base Desktop main menu.
• Configure Delphi data access objects for use 3 Click the Browse button and select the follow-
with the Report Explorer ing directory:
• Use the Report Designer and Report Explorer C:\Program Files\Common Files\Borland
components Shared\Data
Note: Paradox tables are used here because they Note: The + symbol in the Type of the ItemId field
are accessible to all users of Delphi. You can create indicates that this an AutoIncrement field. The
these tables in any database format you prefer. For asterisk indicates that it is also a key field. The
an example of a database-specific end-user appli- Name field is Alpha 60. The FolderId field is an
cation for your database, see integer. The @ symbol used for the Modified and
RBuilder\Demos\EndUser Databases. Deleted fields indicates a datatime type. The B on
the template field indicates binary. If you set the
8 Locate the Table properties drop-down list on
Report.Template.Format to ftASCII, you can use a
the right corner of the dialog.
memo field instead. The ItemType field contains
9 Expand this list and select the Secondary an integer indicating whether the item is a report,
Indexes option. data module, or code module.
10 Click the Define button. Add the ParentId field 2 Locate the Table properties drop-down list on
to the Indexed fields list and click the OK button. the right corner of the dialog.
Name the index ixParentId. Click OK.
3 Expand this list and select the Secondary
11 Click the Save As button and locate the direc- Indexes option.
tory where your DBDEMOS alias is pointed (usu-
4 Click on the Define button. Add the FolderId,
ally C:\Program Files\Common Files\Borland
ItemType, and Name fields to the Indexed fields
Shared\Data). Save the table under the name
list and click the OK button. Name the index
rbFolder.
ixFolderIdItemTypeName.
Create the Item Table
5 Click the Save As... button and locate the direc-
1 Select File | New | Table. Accept the Paradox 7
tory where your DBDEMOS alias is pointed (usu-
table type. Enter the following fields:
ally C:\Program Files\Common Files\Borland
FieldName Type Size Key Shared\Data) and save the table under the name
ItemId + * rbItem.
FolderId I
6 Close Database Desktop.
Name A 60
Size I
ItemType I
Modified @
Deleted @
Template B
411
Building an End-User Reporting Application
APPLICATION TUTORIALS
Create a New Application 6 Select the RBuilder tab of the Delphi compo-
1 Select File | New Application from the Delphi nent palette.
menu. This will create a new project and a blank
form. 7 Add a DBPipeline component to the form.
7 Configure the DBPipeline component: 5 Add daDatMan, daDBBDE to the uses clause of
the form's unit.
DataSource dsItem
Name plItem 6 Select File | Save from the Delphi main menu.
Visible False
Note: The daDatMan unit contains a data manager
Create the ReportBuilder Components class that makes the data workspace available from
within the Report Designer. The daDBBDE unit
1 Add a Report component to the form.
associates a BDE-based dataview class with the
Query Wizard and Query Designer. Therefore,
2 Add a Designer component to the form.
these tools will create instances of this dataview
3 Set the Report property of the Designer to when invoked. This design allows other query dat-
ppReport1. aview classes to be created and associated with
these tools.
4 Add a ReportExplorer component to the
Compile and Run the Application
form. 1 Select the Win32 tab of the Delphi component
5 Set the Designer property of the ReportExplorer palette.
to ppDesigner1. 2 Add a StatusBar to the form.
6 Configure the ReportExplorer component: 3 Configure the StatusBar:
FolderPipeline plFolder Name stbStatusBar
ItemPipeline plItem SimplePanel True
Configure the Designer Component 4 Add a Button component to the form.
1 Select the Designer component.
5 Configure the Button:
2 Expand the DataSettings property in the Object
Name btnLaunch
Inspector.
Caption Launch
3 Set the DatabaseName property to DBDEMOS.
6 Add the following code to the OnClick event of
Note: This property specifies the database that will the button:
be queried.
if not(ppReportExplorer1.Execute) then
4 Set the SQLType to sqBDELocal. stbStatusBar.SimpleText :=
ªppReportExplorer1.ErrorMessage;
Note: Since we’re using Local SQL via the BDE, Note: This code calls the Execute method to
we need to set the SQL type. If you are not using invoke the Report Explorer. If we have not config-
Local SQL to access Paradox and dBase tables, ured one of the Report Explorer properties cor-
you should use an SQLType of sqSQL1, since the rectly, the form will not be displayed, False will be
Local SQL format is not compatible with most returned, and the reason for the failure will be dis-
other databases. played in our status bar.
413
Building an End-User Reporting Application
APPLICATION TUTORIALS
7 Select Project | Compile rbEUProj. Fix any 10 Close the Report Designer.
compilation problems.
11 The 'Annual Sales' report should be displayed in
8 Select File | Save from the Delphi main menu. the 1998 folder.
9 Run the Project. Note: You can create and configure reports from
this point, just as you would from within Delphi.
10 Click the Launch button. The Report Explorer
And as you can see, the Report Explorer is quite
should be displayed. If the Report Explorer is not
easy to use due to its similarity to the Windows
displayed, an explanation will be displayed in the
Explorer.
panel at the bottom of the window.
The running application should look like this:
Create New Folders
1 Select File | New | Folder from the Report
Explorer main menu.
• Configure Delphi data access objects for use 2 Select File | Working Directory from the Data-
with the Data Dictionary base Desktop main menu.
• Configure the Data Dictionary component 3 Click the Browse button and select the follow-
ing directory:
• Use the Query Wizard within the Report
Designer C:\Program Files\Common Files\Borland
Shared\Data
7 Enter the following fields in the dialog: Note: The TableName represents the raw table
name of the database table. The TableAlias will be
FieldName Type Size Key
displayed to the end user using dot notation (i.e.
TableName A 60 *
TableAlias.FieldAlias).
FieldName A 60 *
FieldAlias A 60 Note: This tutorial uses Paradox tables simply
Selectable A 1 because most Delphi developers have access to this
Searchable A 1 type of table. You can use whatever database for-
Sortable A 1 mat you desire when creating these tables.
DataType A 60
2 Click the Save As button and locate the direc-
AutoSearch A 1
tory where your DBDEMOS alias is pointed (usu-
Mandatory A 1
ally C:\Program Files\Common Files\Borland
Note: The TableName and FieldName fields make Shared\Data) and save the table under the name
up the primary key. The FieldAlias is the value rbTable.
that will be displayed to the end user. The Field-
Create the Join Data Dictionary Tables
Name is the raw field name from the database
1 Select File | New | Table. Accept the Paradox 7
table. The TableName is the raw table name of the
table setting. Enter the following fields in the dia-
database table.
log:
8 Click the Save As button and locate the direc-
FieldName Type Size
tory where your DBDEMOS alias is pointed (usu-
TableName1 A 60
ally C:\Program Files\Common Files\Borland
TableName2 A 60
Shared\Data) and save the table under the name
JoinType A 60
rbField.
FieldNames1 A 255
Create the Table Data Dictionary Table FieldNames2 A 255
1 Select File | New | Table. Accept the Paradox 7 Operators A 60
table setting. Enter the following fields in the Cre-
2 Click the Save As button and locate the direc-
ate Paradox 7 Table dialog:
tory where your DBDEMOS alias is pointed (usu-
FieldName Type Size Key ally C:\Program Files\Common Files\Borland
TableName A 60 * Shared\Data) and save the table under the name
TableAlias A 60 rbJoin.
Open the End-User Application 6 Select the RBuilder tab of the Delphi compo-
1 Select File | Open Project from the Delphi nent palette.
menu.
7 Add a DBPipeline component to the form.
2 Open the rbEUProj project from the previous
tutorial. If you have not completed this tutorial, 8 Configure the DBPipeline component:
you can create a new project and add the rbEndUsr
DataSource dsTable
form from the RBuilder\Tutorials directory.
Name plTable
3 Open the rbEndUsr form and save it under the Visible False
name 'rbEUDD' in the My RB Tutorials directory
Create Data Access Components for
(established on page 181).
the Field Table
Note: Save your work frequently to avoid losing 1 Add a Table component to the form.
changes should your computer unexpectedly lose
2 Configure the Table component:
power or crash.
DatabaseName DBDEMOS
4 Select File | Save Project As from the Delphi
Name tblField
menu and save the project under the name rbEUD-
TableName rbField.db
DProj in the My RB Tutorials directory.
3 Add a DataSource component to the form.
Create Data Access Components for
the Tables 4 Configure the DataSource component:
1 Select the Data Access tab of the Delphi compo-
DataSet tblField
nent palette.
Name dsField
2 Add a Table component to the form.
5 Select the RBuilder tab of the Delphi compo-
3 Configure the Table component: nent palette.
DataSet tblTable
Name dsTable
Adding Data Dictionary Support to the End-User Application
418 APPLICATION TUTORIALS
2 Configure the Table component: 2 Right-click over the white space of the Tables
tab and select Generate. The tables will generate.
DatabaseName DBDEMOS
Name tblJoin 3 Click the Fields tab and then generate the
TableName rbJoin.db entries.
3 Add a DataSource component to the form. 4 Click the Joins tab. Right-click and select the
Add menu option. The join panel will appear.
4 Configure the DataSource component:
5 Select Customer.db from the table list on the
DataSet tblJoin
left.
Name dsJoin
6 Select Left Outer from the Join Type drop-down
5 Select the RBuilder tab of the Delphi compo-
list.
nent palette.
7 Select Orders from the table list on the right.
6 Add a DBPipeline component to the form. The suggested join fields will appear in the Joined
Fields section of the panel.
7 Configure the DBPipeline component:
8 Double-click on TaxRate to remove it from the
DataSource dsJoin
join selection.
Name plJoin
Visible False 9 Click Save.
Create the Data Dictionary Component 10 Right-click and select Add. The join panel will
appear.
1 Add a DataDictionary component to the
form. 11 Select Orders.db from the table list on the left.
2 Configure the DataDictionary component: 12 Select Left Outer from the Join Type drop-down
list.
AutoJoin True
BuilderSettings.DatabaseName DBDEMOS 13 Select Employee from the with table list on the
FieldPipeline plField right. The suggested join fields will appear in the
JoinPipeline plJoin Joined Fields section of the panel.
TablePipeline plTable 14 Click Save.
3 Select File | Save from the Delphi main menu. 15 Close the Data Dictionary Builder.
419
Adding Data Dictionary Support to the End-User Application
APPLICATION TUTORIALS
• Replace the Report Explorer form with a form of 2 Open the rbEUProj project from the “Building
your own an End-User Application” tutorial. If you have not
completed this tutorial, you can create a new
• Use the ppRegisterForm procedure
project and open the rbEndUsr form from the
RBuilder\Tutorials directory.
5 Select the panel at the top of the form (named 10 Add rbExpFrm to the project and remove the
tbrExplorer) and use the Object Inspector to set the form from the project's auto-create list (Options |
color to clMaroon. Forms tab).
6 Scroll to the bottom of the form unit and inspect 11 Select File | Save from the Delphi main menu.
the initialization section. It should contain the fol-
12 Run the application. When you click the
lowing:
Launch button you should see a maroon toolbar
initialization instead of a silver one (indicating that the custom
ppRegisterForm(TppCustomReportExplorer, explorer form is being used).
ªTrbReportExplorerForm);
Note: As you can see, you now have total control
finalization
over the look, feel, and behavior of the Report
ppUnRegisterForm(TppCustomReportExplorer);
Explorer form. If you review the source of this
end.
form, you'll see that it is calling various functions
Note: The Delphi Code Editor automatically in the Report Explorer component. These func-
changed the class name of the form from ppRepor- tions are documented in the help.
tExplorerForm to rbReportExplorerForm when
you changed the form name in the Object Inspec- The customized run-time application should look
tor. This call will replace the 'official' explorer like this:
form with the new form we've created.
4 Find the Connect statement at the top of the file Note: Do not modify the table or index definitions.
and review the database, user name, and password Do not add field constraints such as NOT NULL or
parameters. The database name is configured to UNIQUE. Do not define a primary key. The
access the employee demo database that is installed Report Explorer is designed to support desktop and
with InterBase. Modify the parameters as needed client/server databases. This requirement limits
to reflect your InterBase installation. the flexibility of the table definitions. Adding field
constraints such as those described above will
CONNECT "C:\Program Files\Common
ªFiles\Borland Shared\Data\employee.gdb" result in Delphi run-time errors in your end-user
ªUSER "SYSDBA" PASSWORD "masterkey"; reporting application.
5 Review the create statements for the folder
table. The table is created first, followed by two
indexes. Next a generator and a trigger are created
for the folder_id value.
COMMIT;
SET TERM !! ;
CREATE TRIGGER set_folder_id FOR rb_folder
BEFORE INSERT
AS
BEGIN
new.folder_id = gen_id(folder_id_gen, 1);
END !!
SET TERM ; !!
COMMIT;
425
Building a Report Application using InterBase
APPLICATION TUTORIALS
6 Review the create statements for the item table. 3 Enter 'masterkey' as the password and click OK.
The table is created first, followed by two indexes.
4 Right-click to access the popup menu for the
Next, a generator and a trigger are created for the
database. Select 'ISQL' to access the InterBase
item_id value.
ISQL utility.
Run the Create Tables SQL Script
5 Select 'File | Run an ISQL Script' from the main
1 Select Database | Explore from the Delphi main
menu of the InterBase ISQL utility. Open the
menu to access the Database Explorer
ExploreTables.sql file. A 'Save output to a file?'
2 Double-click the database alias corresponding dialog will be displayed.
to your Interbase database. The alias for a default
6 .Click the No button.
installation of the local InterBaser server is IBLO-
CAL.
COMMIT;
SET TERM !! ;
CREATE TRIGGER set_item_id FOR rb_item
BEFORE INSERT
AS
BEGIN
new.item_id = gen_id(item_id_gen, 1);
END !!
SET TERM ; !!
COMMIT;
Building a Report Application using InterBase
426 APPLICATION TUTORIALS
Note: The SQL script should connect to the data- Create Data Access Components for
base and create the database objects. If you receive the Folder Table
a message indicating the script completed with 1 Select the Data Access tab of the Delphi compo-
errors, then review the output information - error nent palette.
messages are displayed following the statement in
2 Add a Database component to the form.
which the error occurred.
3 Configure the Database component:
7 Close the InterBase ISQL window.
AliasName IBLocal
8 Close the Database Explorer.
DatabaseName rbData
Create a New Application Name rbData
1 Select File | New Application from the Delphi LoginPrompt False
main menu. This will create a new project and Params USER NAME=SYSDBA
blank form. PASSWORD=masterkey
2 Set the Form name to 'frmEndUserInterBase'. 4 Test the database connection by setting the Con-
nected property of the Database component to
3 Set the form's Caption to End-User Reporting
True. Resolve any errors and reset the property to
Solution.
False.
4 Select File | Save As from the Delphi menu and
5 Add a Table component to the form.
save the form under the name rbEUIB in the My
RB Tutorials directory (established on page 181). 6 Configure the Table component:
Note: For simplicity, we've defined our database Note: First we set the SQLHourGlass property to
tables so that the table field names correspond False. We do not want the cursor to be displayed
closely with the ItemFieldName and FolderField- when using the Report Explorer to create folders
Name properties. The exception is the item_size and reports. Next, we called the Execute method to
field, which is assigned to the ItemField- invoke the Report Explorer. If we have not config-
Names.Size property. 'Size' is a reserved word in ured one of the Report Explorer properties cor-
InterBase and therefore cannot be used as a field rectly, the form will not be displayed and False will
name. be returned. The reason for the failure will be dis-
played in the 'status bar.'
Note: While it is acceptable to name the fields dif-
ferently in your database table, it is not acceptable 7 Add the following units to the 'uses' clause at
to change the data types or other field attributes, as the top of the form unit: daDatMan, daDBBDE.
the Report Explorer relies on these names.
Note: The daDatMan unit contains a data manager
Run the Application class that makes the data workspace available from
1 Select the Win32 tab of the Delphi component within the Report Designer. The daDBBDE unit
palette. associates a BDE-based dataview class with the
Query Wizard and Query Designer. Therefore,
2 Add a StatusBar to the form.
these tools will create instances of this dataview
3 Configure the StatusBar component: when invoked. This design allows other query dat-
aview classes to be created and associated with
Name stbStatusBar
these tools.
SimplePanel True
8 Select Project | Compile rbEUIBProj. Fix any
4 Add a Button component to the form.
compilation problems.
5 Configure the Button component:
9 Select File | Save from the Delphi main menu.
Name btnLaunch
10 Run the Project.
Caption Launch
11 Click the Launch button. The Report Explorer
6 Add the following code to the OnClick event
should be displayed.
handler of the button:
Session.SQLHourGlass := False; Note: If the Report Explorer is not displayed, an
if not(ppReportExplorer1.Execute) then
explanation will be given in the panel at the bottom
stbStatusBar.SimpleText:= of the window.
ªppReportExplorer1.ErrorMessage;
429
Building a Report Application using InterBase
APPLICATION TUTORIALS
Create New Folders Note: You can create and configure reports from
1 Select File | New | Folder from the Report this point, just as you would from within Delphi.
Explorer main menu. And as you can see, the Report Explorer is quite
easy to use due to its similarity to the Windows
2 Type Marketing in the folder name and press the
Explorer.
Enter key.
Note: Using the Data Dictionary is optional. The
3 Select the main folder (entitled All Folders).
SQL script for adding the Data Dictionary tables is
4 Right-click over the white space of the Folder called DataDictTables.sql and is located in the
Tree and select the New Folder option from the RBuilder\Tutorials directory. You can refer to the
popup menu. tutorial called “Adding Data Dictionary Support to
the End-User Application” for additional informa-
5 Type Accounting in the folder name and press
tion on configuring the relevant components and
the Enter key.
properties.
6 Right-click over the white space of the Folder
Tree and select the New Folder option. A folder
should be created under the Accounting folder.
APPENDIX
digital-metaphors.public.reportbuilder.component-writing
custom report components, datapipelines, and
devices
digital-metaphors.public.reportbuilder.beta
beta program for upcoming releases
Further Support
The newsgroups are an excellent resource for tech-
nical support, but if you prefer other methods, they
are available:
• Mail: support@digital-metaphors.com
• Phone: 972.931.1941
• Fax: 972.931.7865
433
Index
INDEX
A Visible property of 20
BarCode
Address description of 30, 96
example code for 69 BDE Alternatives
Advanced Component Palette 98 Advantage 55
AfterPrint event 65 Apollo 55
Align 101 Flash Filer 55
Align or Space Toolbar InfoPower 55
description of 101 ODBC Express 55
usage of 231, 250 ODBC98 55
AllowDataSettingsChange property 153 Opus 55
AllowEditSQL property 181 Titan 55
AllowPrintToArchive property 121 BDE Support 53
AllowPrintToFile property 123 BDEPipeline 49
AllowSaveToFile property 153 about 49
application deployment 131, 225 description of 27, 151
applications BeforePrint event 65
Adding Data Dictionary Support to the End-User BinName property 119
App 415 BLOB field 132
Building a Report App. using InterBase 423 bookmarks
Building a Reporting Application 401 limiting data traversal using 51
Building an End-User Reporting App. 409 BottomOffset property 33
archive usage of 275
print report to 121 bounding box method 233
ArchiveFileName property 121 Bring to Front
ArchiveReader Component Report Tree and 17
description of 27, 152
ASCII C
about 123
Calc Workspace 148, 193
Average 19
Code Editor 196
B Code Explorer 194
Code Toolbox 197
bands 14 overview 193
BeforePrint event of 20 CalcOrder property 73
detail 4, 8 CalcType property 75
dynamic 20 calculated fields 19
footer 4, 234 calculations
header 4, 7 performing 19, 73
PrintHeight property of 20 CheckBox
resizing 15 description of 30, 96
summary 265 Code Editor 196
title 325 Code Explorer
events view 194
global scoping 196
module view 195
variables view 194
Code reports
how to 83
Index
434
Code Toolbox usage of 351
Data tab 198 Configuring Reports 67
Language tab 199 Continued Group
Objects tab 198 example code for 70
CodeSite Controlling Data Traversal
compiling 213 about 50
CodeSite functions Copies property 119
using 212 Count
Collation property 119 about 74
columns calculating 19
using to create mailing labels 329 Master/Detail records 75
component Crosstab Component
selection description of 31, 98
Ctrl-click method 232 usage of 350
Shift-click method 233 Crosstab Designer 350
visibility 20 Crosstab report
component editor 15 creating 349
Component Palette 13 Cumulative Sum
components about 78
ArchiveReader 27, 152 CustomDataPipeline class 61
BarCode 30, 96 CustomPreviewer class 117
BDEPipeline 27, 151
CheckBox 30, 96 D
CrossTab 31, 98 daCustomDataView class 183
DataDictionary 152 daDataSet class 184
DBBarCode 31, 97 daDataView class 183
DBCalc 31, 97 DADE
DBCheckBox 31, 97 about 167
DBImage 31, 97 architecture 183
DBMemo 30, 97 configuring 181
DBPipeline 27, 151 extending 185
DBRichText 31, 97 daQueryDataView class 184
DBTeeChart 31, 97 daSession class 184
DBText 30, 97 daSQL class 184
Designer 152 data
Image 30, 96 filtering 19
JITPipeline 27, 151 data access
Label 8, 96 about 53
Memo 29, 96 data pipeline types 49
Region 31, 98 description of 25
Report 27, 151 objects
ReportExplorer 152 configuring 7
RichText 29, 96 Data Access Development Environment
Shape 30, 96 See DADE
SubReport 31, 98 Data Component Palette
SystemVariable 30, 96 description of 97
TeeChart 30, 96 Data Dialog 94
TextPipeline 27, 151 Data Dictionary 159
Variable 30, 96 data module 132, 226
Viewer 27, 151 data pipelines
Concatenation BookmarkList property of 51
example code for 68 dataviews and 167
Conditional Grand Total in Data Tree 8
about 80 RangeBegin property of 51
Conditional Group Total RangeEnd property of 51
about 79 retrieving field values via 59
Configure property Data Process 25
435
Index
G J
generation 5, 115 JITPipeline
grand total about 49, 59
about 77 description of 27, 151
conditional 77 usage of 341
group L
creating a 257
group header band Label Component
conditional regions in 71 description of 96
groups usage of 248
’Continued...’ label and 70 Label Template Wizard
creating via the Report Wizard 110 usage of 331
totals in 76 labels
two pass totals in 81 created for mailing 329
Groups Dialog 93 language support
Groups, Calculations, and the Summary Band re- about 139
port custom translations 141
creating 255 default language 140
Line Component
H usage of 250
Header Band lookup tables/queries 19
about 4 M
usage of 7
horizontal ruler mailing labels
options for units of measurement 249 creating 329
HTML 127 MailMerge
usage of 347
Main 23, 145
MaintainAspectRatio
usage of 274
Margins property 119
Master/Detail report
creating a 289
Master/Detail/Detail report
creating a 303
Maximum 19
Memo Component
description of 29, 96
OverFlow property 34
Stretch property 34
stretching 20
437
Index
Minimum 19 Q
ModalForm property 157
MS Access Query Designer
SQLType 181 adding search criteria via 173–175
MS SQL Server concatenating fields via 178–179
SQLType 181 creating an SQL GROUP BY via 175–177
editing SQL generated by 180
N usage of 173
Query Wizard
Native Access to Proprietary Data 61
about 169
Nudge Toolbar 102
Create a Simple Query-Based Dataview via 169–
O 172
OnCalc 20 R
OnCalc event 73
raf file extension 121
OnCalcFields event 19
RAP 201
OnCancel event 66
about 191
On-Line Help 163
Calc Workspace 193
OnPreviewFormCreate event 66
classes
OnPrint event 67
adding 210
OnReset event 73
CodeSite
Oracle
support 211
SQLType 181
using 212
Orientation property 119
configuring 205
OverFlowOffset property 33
debugging 211
P end user configurations 205
event handlers
packages 137 coding 201
page objects 116 compiling 202
Page Setup Dialog 92 extending 209
page style 43 functions
PageLimit 16 adding 209
PaperHeight property 119 calling 204
PaperName property 119 pass-through 209
PaperWidth property 119 global constants 203
Paradox global procedures 203
SQLType 181 global variables 202
Performing Calculations 73 local constants 202
Preview Tab 89 local variables 202
Preview workspace 149 parameters 204
previewing 117 pass-through functions 209
Print Dialog 91 programs 201
print method 121 properties
print preview form 115 adding 210
customized 405 tutorials
Print to ASCII Text file 123 Adding Functions to 367
Print to File Setup Dialog 93 Concatenating Fields 355
PrinterName property 119 Displaying Delphi Forms from 387
PrinterSetup property 119 Dynamic Duplexing 363
printing Extending RTTI 373
from a Text File 337 Printing Description of AutoSearch Criteria 373
to a Text File 333 RAPInterface property 153
to printer 115 RAPOptions property 153
to screen 115
printing settings 119
Index
438
Region Component report engine
description of 31, 98 data traversal and the 50
example code for 71 Report Explorer
used to logically group dynamic components 271 about 217
report Customizing the Report Explorer Form 421
A Simple Report the Hard Way 247 description of 157
archiving 121 toolbar 217
Creating a Report Via the Data Tree 229 report layout
Creating a Report Via the Report Wizard 237 about 25
creating from an ancestor class 402 saving to a database 134
deployment 131, 225 saving to a file 133
emulation 125 report outline
End-User Report Solution 154 See Report Tree
loading and saving 134 report output 25
PageLimit property 16 Report property 153
print method 9 report templates 133
selecting 15 Report Tree
tabular about 17
creating 238 description of 95
templates 133 Report Wizard
vertical creating a report via the 237
creating 240 creating a simple report via the 107–109
Report Archive File 121 creating groups via the 110–111
Report Component Report.Template.Format property 133
description of 27, 151 ReportBuilder
usage of 7 Delphi components of 27
Visible property of 20 fundamentals 25–141
report components 29–31 ReportBuilder Enterprise
report creation Delphi Components of 151
design 4 deploying 225
generation 5, 115 fundamentals 147–226
process 4 ReportExplorer Component
select 3 description of 152
Report Designer folder table of 217
about 89 item table of 217
usage of 283 ReportTextFile device 125
working with the 15 ReprintOnOverFlow property 33
Report Emulation Text File 125 ResetGroup property 75
RichText Component
description of 29, 96
usage of 346
RichText editor
usage of 347
RTF 127
rtm file extension 133
rulers 14
run-time packages 137
439
Index