CrysDev: A Developer’s Guide to Integrating Crystal Reports
Craig Berntson
Hentzenwerke Publishing
Published by: Hentzenwerke Publishing 980 East Circle Drive Whitefish Bay WI 53217 USA Hentzenwerke Publishing books are available through booksellers and directly from the publisher. Contact Hentzenwerke Publishing at: 414.332.9876 414.332.9463 (fax) www.hentzenwerke.com
[email protected] CrysDev: A Developer’s Guide to Integrating Crystal Reports By Craig Berntson Technical Editor: Dan Jurden Copy Editor: Nicole McNeish Cover Art: “Crystal” by Todd Gnacinski, Milwaukee, WI Copyright © 2003 by Craig Berntson All other products and services identified throughout this book are trademarks or registered trademarks of their respective companies. They are used throughout this book in editorial fashion only and for the benefit of such companies. No such uses, or the use of any trade name, is intended to convey endorsement or other affiliation with this book. All rights reserved. No part of this book, or the ebook files available by download from Hentzenwerke Publishing, may be reproduced or transmitted in any form or by any means, electronic, mechanical photocopying, recording, or otherwise, without the prior written permission of the publisher, except that program listings and sample code files may be entered, stored and executed in a computer system. The information and material contained in this book are provided “as is,” without warranty of any kind, express or implied, including without limitation any warranty concerning the accuracy, adequacy, or completeness of such information or material or the results to be obtained from using such information or material. Neither Hentzenwerke Publishing nor the authors or editors shall be responsible for any claims attributable to errors, omissions, or other inaccuracies in the information or material contained in this book. In no event shall Hentzenwerke Publishing or the authors or editors be liable for direct, indirect, special, incidental, or consequential damages arising out of the use of such information or material. ISBN: 1-930919-38-7 Manufactured in the United States of America.
This book is dedicated to the memory of my dear friends, Tom Piper and Ed Rauh. Tom, may you go barefoot through the eternities. Ed, even when you knew you were dying, you kept pressing on. May we learn from your example, and may we always remember you both. —Craig Berntson
v
Our Contract with You, The Reader In which we, the folks who make up Hentzenwerke Publishing, describe what you, the reader, can expect from this book and from us.
Hi there! I’ve been writing professionally (in other words, eventually getting a paycheck for my scribbles) since 1974, and writing about software development since 1992. As an author, I’ve worked with a half-dozen different publishers and corresponded with thousands of readers over the years. As a software developer and all-around geek, I’ve also acquired a library of more than 100 computer and software-related books. Thus, when I donned the publisher’s cap five years ago to produce the 1997 Developer’s Guide, I had some pretty good ideas of what I liked (and didn’t like) from publishers, what readers liked and didn’t like, and what I, as a reader, liked and didn’t like. Now, with our new titles for 2002, we’re entering our fifth season. (For those who are keeping track, the ’97 DevGuide was our first, albeit abbreviated, season, the batch of six “Essentials” for Visual FoxPro 6.0 in 1999 was our second, and, in keeping with the sports analogy, the books we published in 2000 and 2001 comprised our third and fourth.) John Wooden, the famed UCLA basketball coach, posited that teams aren’t consistent; they’re always getting better—or worse. We’d like to get better… One of my goals for this season is to build a closer relationship with you, the reader. In order for us to do this, you’ve got to know what you should expect from us. •
You have the right to expect that your order will be processed quickly and correctly, and that your book will be delivered to you in new condition.
•
You have the right to expect that the content of your book is technically accurate and up-to-date, that the explanations are clear, and that the layout is easy to read and follow without a lot of fluff or nonsense.
•
You have the right to expect access to source code, errata, FAQs, and other information that’s relevant to the book via our Web site.
•
You have the right to expect an electronic version of your printed book to be available via our Web site.
•
You have the right to expect that, if you report errors to us, your report will be responded to promptly, and that the appropriate notice will be included in the errata and/or FAQs for the book.
Naturally, there are some limits that we bump up against. There are humans involved, and they make mistakes. A book of 500 pages contains, on average, 150,000 words and several megabytes of source code. It’s not possible to edit and re-edit multiple times to catch every last
vi misspelling and typo, nor is it possible to test the source code on every permutation of development environment and operating system—and still price the book affordably. Once printed, bindings break, ink gets smeared, signatures get missed during binding. On the delivery side, Web sites go down, packages get lost in the mail. Nonetheless, we’ll make our best effort to correct these problems—once you let us know about them. In return, when you have a question or run into a problem, we ask that you first consult the errata and/or FAQs for your book on our Web site. If you don’t find the answer there, please e-mail us at
[email protected] with as much information and detail as possible, including 1) the steps to reproduce the problem, 2) what happened, and 3) what you expected to happen, together with 4) any other relevant information. I’d like to stress that we need you to communicate questions and problems clearly. For example… •
“Your downloads don’t work” isn’t enough information for us to help you. “I get a 404 error when I click on the Download Source Code link on www.hentzenwerke.com/book/downloads.html” is something we can help you with.
•
“The code in Chapter 10 caused an error” again isn’t enough information. “I performed the following steps to run the source code program DisplayTest.PRG in Chapter 10, and I received an error that said ‘Variable m.liCounter not found’” is something we can help you with.
We’ll do our best to get back to you within a couple of days, either with an answer or at least an acknowledgment that we’ve received your inquiry and that we’re working on it. On behalf of the authors, technical editors, copy editors, layout artists, graphical artists, indexers, and all the other folks who have worked to put this book in your hands, I’d like to thank you for purchasing this book, and I hope that it will prove to be a valuable addition to your technical library. Please let us know what you think about this book—we’re looking forward to hearing from you. As Groucho Marx once observed, “Outside of a dog, a book is a man’s best friend. Inside of a dog, it’s too dark to read.” Whil Hentzen Hentzenwerke Publishing April 2003
vii
List of Chapters Chapter 1: Introducing Crystal Reports Chapter 2: Touring Crystal Reports Chapter 3: Creating Your First Report Chapter 4: Accessing Data Chapter 5: Intermediate Reporting Chapter 6: Advanced Reporting Chapter 7: Subreports Chapter 8: Using Formulas Chapter 9: The RDC: Introduction, Printing, and Databases Chapter 10: The RDC: Manipulating Data Chapter 11: The RDC: Formatting the Report Chapter 12: Previewing the Report at Runtime Chapter 13: The Report Designer Control Chapter 14: Exporting Reports Chapter 15: Integrating COM Components Chapter 16: Web Reporting Chapter 17: Crystal Reports .NET Chapter 18: Licensing and Distribution Chapter 19: Crystal Reports Tools
1 17 51 73 105 133 149 163 189 225 245 283 303 313 343 357 385 401 417
ix
Table of Contents Our Contract with You, The Reader Acknowledgements About the Author How to Download the Files Chapter 1: Introducing Crystal Reports Crystal Reports versions Installing Crystal Reports What’s changed in version 9 What’s missing What’s new Upcoming chapters Summary
Chapter 2: Touring Crystal Reports Report Experts Data page Links page Fields page Grouping page Summaries page Group Sorting page Chart page Record Selection page Template page Blank Reports The Crystal Reports desktop Menus Toolbars Status bar Design page Preview page Report Sections Section Expert Formatting report objects Common page Border page Font page Paragraph page Hyperlink page Resizing and moving objects
iii xvii xix xxi
1 2 2 13 13 14 14 15
17 17 17 17 18 18 18 18 18 18 18 19 19 19 25 28 28 29 30 30 31 32 33 34 35 36 36
x Using the mouse Using the keyboard The Object Size and Position window Guidelines Setting options Application options Report options The report-processing model Pre-pass 1 Pass 1 Pre-pass 2 Pass 2 Pass 3 Summary
Chapter 3: Creating Your First Report Designing the report Sketching the report The report data Your first report, step-by-step Selecting the data source Adding data fields to the report Adding a calculated field Grouping and group totals Formatting the report Adding the page header Charting made easy Summary
Chapter 4: Accessing Data Using the Database Expert Creating a new connection Selecting database objects Linking tables Field definitions files Creating a field definition file Using a field definition file Working with images Images in the database Adding a watermark Limiting records selected The Select Expert Miscellaneous data functions Set Database Location LogOn or Off Server Show SQL Query
37 37 37 37 38 38 46 47 48 48 48 48 48 48
51 51 51 53 53 54 55 58 60 64 66 68 71
73 73 74 87 89 92 92 94 95 96 96 97 98 100 100 100 101
xi Perform Grouping on Server Report Bursting Indexes Summary
Chapter 5: Intermediate Reporting Understanding the Crystal Repository Adding objects to the repository Using repository objects in a report Updating objects in the repository Sorting Groups Drill-down Hierarchical groups Summaries Subtotals and grand totals Running totals Cross-tabs Charts Basic charting Advanced charting Maps The Data tab The Type tab The Text tab Summary
Chapter 6: Advanced Reporting Report parameters Multiple-value parameters Default values Report alerts OLE objects Embedded fields Hierarchical reports Summary
102 102 103
105 105 106 107 107 108 108 113 113 114 114 116 117 123 124 128 129 129 130 131 132
133 133 135 137 139 142 144 146 147
Chapter 7: Subreports
149
Inserting a subreport Unlinked subreports Linked subreports On-demand subreports Updating subreports Summary
149 150 157 159 160 162
xii
Chapter 8: Using Formulas The Formula Editor The General toolbar The Workshop toolbar The Custom Function toolbar The Workshop Tree The Editor toolbar Understanding formulas Comments Data types Variables Fields Operators Functions Custom functions The Formula Extractor The Formula Expert Summary
Chapter 9: The RDC: Introduction, Printing, and Databases Understanding the Report Design Component Getting started with RDC programming Registering the runtime component Working with collections The Application object The Report object The Database object Working with tables Passing stored procedure parameters The DatabaseTable object The ConnectionProperties object Working with the ConnectionProperties object Getting connection property information Working with fields Linking tables Connecting to data—some examples Logging on and off a server database Connecting to ADO Connecting through an ODBC connection Connecting to XML Connecting to file-based data You connected to your data, now what? Summary
163 165 167 167 168 168 169 171 171 171 174 174 175 182 183 185 186 187
189 190 190 192 194 195 199 206 207 209 209 211 211 213 214 215 217 217 218 219 220 220 220 223
xiii
Chapter 10: The RDC: Manipulating Data Sorting Working with Groups Summary Fields Running Totals SQL Expressions Formula Fields Parameter Fields Report Alerts Summary
225 225 226 228 231 234 236 237 241 243
Chapter 11: The RDC: Formatting the Report
245
Working with Areas Condition Formulas Working with Sections The ReportObject object TextObject object Field elements LineObject object BoxObject object FieldObject object Picture fields Special variable fields Summary fields BlobFieldObject object Crosstabs GraphObject object The FieldDefinitions collection MapObject object OLEObject OLAPGridObject object The ObjectSummaryFieldDefinitions collection Unbound fields Subreports Summary
245 248 249 251 251 253 257 257 258 263 263 265 265 267 269 275 276 276 278 279 279 280 282
Chapter 12: Previewing the Report at Runtime Registering the control Creating a preview form Methods of the Viewer Control Showing the report Retrieving information
283 283 284 291 291 293
xiv Events Report objects events Drill events Toolbar objects events Miscellaneous events Summary
Chapter 13: The Report Designer Control Registering the Control Creating a design form Working with the designer Providing Help Using the Designer Control Summary
294 295 297 297 299 301
303 303 304 310 311 312 312
Chapter 14: Exporting Reports
313
Programmatic exports Exporting to files Adobe Acrobat (PDF) Microsoft Word Microsoft Excel Rich Text Format (RTF) HTML XML Comma Separated Values (CSV) Tab-Separated Text Text Report Definition Exporting to an application Exporting to MAPI Exporting to ODBC Summary
314 318 318 319 320 323 325 328 332 334 335 337 338 338 339 341
Chapter 15: Integrating COM Components Formulas revisited Events Report events Section events Separate image files Report variables Summary
343 343 344 344 352 354 355 356
xv
Chapter 16: Web Reporting
357
Report design revisited Embedded hyperlinks Cascading style sheets Navigation Report Parts Working with ASP Page rendering objects Customizing the Viewer The Report Application Server Customizing the RAS The RAS SDK Summary
357 357 359 360 362 364 366 371 372 379 382 384
Chapter 17: Crystal Reports .NET
385
Windows-based applications Web-based applications The Crystal Reports .NET designer Connecting to ADO .NET XML web services Publishing a web service Consuming a web service The CrystalDecisions namespaces Summary
385 388 392 394 396 396 397 398 399
Chapter 18: Licensing and Distribution Distribution RDC distribution Web reporting .NET distribution Licensing The License Manager Summary
Chapter 19: Crystal Reports Tools Documentation files The Crystal Decisions web site Hot fixes and service packs Utilities Support forums Summary
401 401 401 414 414 414 415 416
417 417 418 419 420 421 421
xvi
xvii
Acknowledgements I remember sitting down at dinner at the hotel restaurant the night before the Great Lakes Great Database Workshop in 2000. Whil Hentzen, sitting next to me, leaned over and said “So, about this book you’re writing.” We had discussed the possibility in passing a few times before that, but nothing concrete. That was when I started thinking I just might be able to do it. But, it still took a year before I started work on the project. Thanks, Whil, for all your efforts, and for publishing the best collection of development books available. Putting this book together has not been easy. I want to thank my coworkers at 3M HIS, Tony Curtis, Cole Gleave, and Erie Walker. Thanks to the people from the Visual FoxPro community that helped in many ways, Cathi Gero, George Tasker, Cathy Pountney, Ted Roche, Doug Dodge, Nancy Folsom, Ken Cluff, Evan Delay, Rick Schummer, and Cindy Winegarden. I’m sure I left out someone, but that doesn’t mean your help wasn’t appreciated. I also need to thank Jaylene Crick and the many support people I worked with at Crystal Decisions. I must not forget the entire Visual FoxPro team at Microsoft. Especially Brad Peterson, Calvin Hsia, Ken Levy, and my good friend John Koziol. These guys have flat out produced the best development tool you can find. I have to thank my Tech Editor, Dan Jurden and my copy editor, Nicole McNeish. I can’t forget Mom and Dad. Finally, I need to thank my boys, Johnathan and Jason. There were many hours and days that I wasn’t there because of this book. Thank you for your understanding.
xviii
xix
About the Authors Craig Berntson Craig has been developing custom and commercial applications for business and government for 20 years. He has developed applications for small business as well as large enterprises. He uses Visual FoxPro, C++, and Crystal Reports as his main development tools. He has written several articles for FoxTalk, some of which are available on the MSDN web site. He has also spoken at many software developer conferences, seminars, and user groups, including Advisor Visual FoxPro DevCon, the Great Lakes Great Database Conference, Essential Fox, and MSDN events. Craig is a Microsoft Certified Solution Developer and has been named a Microsoft Most Valuable Professional every year since 1997 for his support of the Visual FoxPro community. You can often find him online at the Universal Thread (www.universalthread.com). Craig is the President of the Salt Lake City FoxPro User Group where he frequently gives presentations on using Visual FoxPro and other current and emerging technologies. He is currently a Senior Software Engineer at 3M Health Information Systems in Salt Lake City. e-mail:
[email protected], Web: www.craigberntson.com
Dan Jurden Dan Jurden is a Senior Application Developer for EPS-Software Corp. located in Houston, Texas. He is a Microsoft Certified Professional. He co-authored the book Creating Visual FoxPro Applications using Visual FoxExpress with BOb Archer, published by Hentzenwerke Publishing. He has also authored articles published in CoDe Magazine and Universal Thread Magazine dealing with SQL Server and other topics. Dan has presented topics at the German DevCon, Essential Fox, SQL Server Live!, and GLGDW conferences. He has been developing Client-Server applications using SQL Server and Crystal Reports for over 6 years. Dan can be reached via email at
[email protected].
xx
xxi
How to Download the Files Hentzenwerke Publishing generally provides two sets of files to accompany its books. The first is the source code referenced throughout the text. Note that some books do not have source code; in those cases, a placeholder file is provided in lieu of the source code in order to alert you of the fact. The second is the e-book version (or versions) of the book. Depending on the book, we provide e-books in either the compiled HTML Help (.CHM) format, Adobe Acrobat (.PDF) format, or both. Here’s how to get them.
Both the source code and e-book file(s) are available for download from the Hentzenwerke Web site. In order to obtain them, follow these instructions: 1.
Point your Web browser to www.hentzenwerke.com.
2.
Look for the link that says “Download”
3.
A page describing the download process will appear. This page has two sections:
•
Section 1: If you were issued a username/password directly from Hentzenwerke Publishing, you can enter them into this page.
•
Section 2: If you did not receive a username/password from Hentzenwerke Publishing, don’t worry! Just enter your e-mail alias and look for the question about your book. Note that you’ll need your physical book when you answer the question.
4.
A page that lists the hyperlinks for the appropriate downloads will appear.
Note that the e-book file(s) are covered by the same copyright laws as the printed book. Reproduction and/or distribution of these files is against the law. If you have questions or problems, the fastest way to get a response is to e-mail us at
[email protected].
Chapter 1: Introducing Crystal Reports
1
Chapter 1 Introducing Crystal Reports What is Crystal Reports? Who should use it? Why should you use it? When should Crystal Reports be used? How do you use it? These are some of the questions that will be answered in this book.
You have probably heard of Crystal Reports. In fact, you probably use it. Why else would you buy this book? I assume you are also a software developer looking for more information on how to use Crystal Reports in your application. After all, the word “develop” is in the title of this book. You’re about to learn that Crystal Reports is a very powerful and flexible reporting tool. However, before digging into the nitty gritty, I will address a few basic questions in case you are new to Crystal Reports or are investigating it for use in your application. Many years ago, I took a high school journalism class. I don’t remember much from the class, but I do remember one important thing: all good stories answer six questions; who, what, when, where, why, and how. Even though I’m not a journalist today, I think these questions are important to address. I will start with the what. What is Crystal Reports? Simply put, it is a reporting application that creates sophisticated reports from a company called Crystal Decisions. It can pull data from many different data sources and be used stand-alone or embedded in an application. Who should use Crystal Reports? That’s pretty easy. I use Crystal Reports for all my reporting and I think you should too. End users can also use Crystal Reports to pull data from your application, databases, operating system logs, and many other data sources. So, Crystal Reports is for both the developer and end user. Why should you use Crystal Reports? Again, a question with an easy answer. I’m not the type of author who learns a product, writes a book about it, and then moves on to the next product. In fact, my development tool, Visual FoxPro, includes a good built-in reporting tool, but I use Crystal Reports because it gives the user a lot of power in their reporting needs. You will soon see how easy it is to add grouping, graphs, and drill down to reports. When should you use Crystal Reports? As I said earlier, I use Crystal Reports exclusively for reports in applications I develop. I could use the Visual FoxPro report designer for simple reports and Crystal Reports for more sophisticated needs, but by using only one reporting tool, my users have a consistent look and feel across all reports. Where should you use Crystal Reports? Again, in every application you develop. Finally, how do you use Crystal Reports? Well, that’s the purpose of this book. You will see how to seamlessly embed Crystal Reports into your applications.
2
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Crystal Reports versions As I was writing this book, Crystal Reports 9 was released. Some chapters were updated to include new material; others were checked to make sure they were still correct for this release. You should be aware that four editions are available: •
Standard—provides basic reporting capabilities for accessing the most common databases.
•
Professional—adds additional database support such as OLAP and XML plus additional report design features like custom templates, repository, and more.
•
Developer—the base developers version. Gives you report design and runtime distribution capabilities. You also get a license for up to five concurrent users for runtimes and development testing.
•
Advanced—adds advanced development and deployment capabilities. Report queuing and caching as well as report creation and modification SDKs.
If you are developing applications, you should be using either the Developer or the Advanced edition, because they are the only ones that give you both the distributable controls and a license to ship them with your application. If you purchase one of the other versions, an upgrade is available from your reseller or directly from Crystal Decisions.
Installing Crystal Reports Installing Crystal Reports is a simple process. The following steps walk you through the installation: 1.
Insert the Crystal Reports CD into your CR ROM drive. If you have enabled Autostart, the startup window (see Figure 1) displays.
Chapter 1: Introducing Crystal Reports
Figure 1. The startup window displays when you insert the Crystal Reports CD. There are several options available on the left side of the startup screen: •
Release Notes—displays information on installation and system requirements.
•
Technical Resources—launches your web browser and navigates to a Crystal Decisions web site where you can get more information about technical resources such as training, technical support, white papers, etc.
•
Services—navigates to a site that provides an overview of training, consulting, and
certification resources available from Crystal Decisions. •
Web Reporting—displays a web site that discusses Crystal Enterprise, a tool for
enterprise reporting needs. •
Crystal Decisions Products—provides an overview of other products from Crystal Decisions, such as Crystal Enterprise, Crystal Analysis, and several analytical applications.
2.
In the lower right corner of the start up window is the install button. Click Install Crystal Reports 9 to launch the installation wizard. The Welcome to the Installation Wizard (see Figure 2) displays.
3
4
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 2. The welcome page of the Installation Wizard starts you on your way to installing Crystal Reports. 3.
Click Next. The license agreement displays (see Figure 3).
Chapter 1: Introducing Crystal Reports
Figure 3. You must accept the License Agreement to proceed with installation. 4.
If you do not agree with the license agreement, just click Next and the Installation Wizard will abort. If you agree with the license, select I accept the License Agreement, and then click Next to display the User Information page (see Figure 4).
5
6
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 4. Enter your personal information in the User Information page. 5.
Enter your name, organization (if you have one), and your CD Key Code from the back of your CD sleeve. Click Next to display the Installation Type page (see Figure 5.)
Chapter 1: Introducing Crystal Reports
7
Figure 5. The Select Installation Type page allows you to select a Typical, Complete, or Custom installation and choose where you want to install Crystal Reports. 6.
I recommend you choose the Custom installation. This allows you to choose which parts of Crystal Reports you want to install such as maps and database drivers. You should also enter the installation path if you don’t want to use the default. Once you do this, click Next to display the Select Features dialog box (see Figure 6).
8
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 6. The Select Features page allows you customize the components and features you want to install. 7.
I made some changes to my installation. For example, I made changes to the Data Access option, selecting only the data sources I’m interested in using. I also selected all options under Export Support and Geographic Mapping. Once you customize your installation, click Next. The Start Installation page displays (see Figure 7).
Chapter 1: Introducing Crystal Reports
Figure 7. The Start Installation dialog box gives you one last chance to confirm your choices before actually starting the installation. 8.
Click Next to begin the installation. The installation progress page displays (see Figure 8).
9
10
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 8. The installation progress displays once you actually begin the installation. 9.
Once the installation is complete, the Registration Wizard launches. (see Figure 9). Click Next to begin the registration process.
Chapter 1: Introducing Crystal Reports
11
Figure 9. The Registration Wizard walks you through the Crystal Reports registration process. 10. If you have a registration number, enter it in the Registration Options dialog box (see Figure 10). If you don’t have one, you can register your copy of Crystal Reports and obtain a number. I wrote the registration number on my Crystal Reports CD sleeve. That way I have it if I need to reinstall the application. If you don’t want to register Crystal Reports at this time, click Register Later.
12
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 10. You will be asked to register your copy of Crystal Reports as part of the installation process. 11. If you register Crystal Reports or enter the registration number, press Finish to complete the installation process. If you register Crystal Reports, you get a confirmation showing the registration was successful (see Figure 11).
Figure 11. The registration confirmation displays when you successfully register your copy of Crystal Reports.
Chapter 1: Introducing Crystal Reports
13
12. Your installation is now complete (see Figure 12). Click Finish to close the Installation Wizard.
Figure 12. The setup dialog displays when you complete the installation.
What’s changed in version 9? Crystal Reports 9 includes some exciting new features for developers. You will also discover some features found in previous versions are now missing.
What’s missing? Crystal Decisions removed several developer features in this new release, but don’t worry too much about missing functionality. Many of the same functions are implemented in a different way. Some of the removed capabilities include: •
Compiled reports
•
Crystal Dictionary and Crystal SQL Designer
•
Export to Data Interchange Format (DIF), Lotus 123, and Multi-Byte Character Sets (MBCS)
14
CrysDev: A Developer’s Guide to Integrating Crystal Reports •
Developer APIs Cpeaut32.DLL and Crystl32.OCX
•
Database drivers for bound database, Centura SQLBase (Gupta), Essbase, and native Microsoft SQL Server
What’s new? Crystal Reports 9 has many exciting new features for developers, including: •
Enhanced designer. I found report creation to be much easier with Crystal Reports 9.
•
SQL commands. These replace and enhance Crystal SQL Designer.
•
Unicode support.
•
Crystal repository. Makes it easy to reuse report objects. This is a replacement for the Crystal Dictionary.
•
Custom templates. It’s now easy to create and reuse templates, thus giving a common look to all your reports.
•
Report parts. Makes is easy to deploy reports to hand-held devices
•
Custom functions. You can now use the Crystal Reports formula languages to create your own functions.
•
Formula Workshop. An enhancement of the old Formula Expert
•
Side-by-side installation. Different versions of Crystal Reports can now coexist on the came computer.
•
Improved database support.
•
In-place chart editing. You no longer need to launch the Chart Analyzer to customize a chart.
•
Improved Report Design Control (RDC) for application integration.
•
Report Application Server (RAS) for web reporting and distribution.
•
Enhanced formulas, experts, cross tabs, and wizards.
Upcoming chapters As this book is about using Crystal Reports in application development, the rest of the book is devoted to helping you understand how to use Crystal Reports and embed it in your applications. In Part 1, you learn how to design a report. In Chapter 2, “Touring Crystal Reports,” I discuss the Crystal Reports designer and how to set various options to maximize your productivity. Chapter 3, “Creating Your First Report, Step-by-Step,” walks you through creating a report with drill-down and graphing. Chapter 4, “Accessing Data,” presents a
Chapter 1: Introducing Crystal Reports
15
discussion on accessing the most common types of data. In Chapter 5, “Intermediate Reporting,” I show how to sort and group and add graphs, maps, and cross tabs to a report. Chapter 6, “Advanced Reporting” discusses report parameters, alerts, and embedded OLE objects. Chapter 7, “Subreports,” covers using subreports. Crystal Reports also has its own programming language. Chapter 8, “Using Formulas,” discusses this topic in detail. Part 2, moves into programming reports and shows you how to embed Crystal Reports in your application. Programmatically controlling Crystal Reports begins in Chapter 9, “The RDC: Introduction, Printing, and Databases,” where I first present the Report Design Control. The RDC is a big topic and continues in Chapter 10, “The RDC: Manipulating Data”; Chapter 11, “The RDC: Formatting the Report”; Chapter 12, “Previewing the Report at Runtime”; and Chapter 13, “The Runtime Design Component.” Chapter 14, “Exporting Reports,” explains the different export options and some “gotchas” to watch out for. Chapter 15, “Integrating COM Components with Crystal Reports,” shows you how you to call COM components from inside your application. It also discusses hooking into Crystal Reports events. Chapter 16, “Crystal Reports .NET,” discusses Microsoft’s Visual Studio .NET, which ships with a special version of Crystal Reports. Chapter 17, “Web Reporting,” moves on to Internet concepts and how to put your report on the web. Chapter 18, “Distribution and Licensing,” discusses the issues of shipping your reporting solution and additional licensing requirements you may face. Finally, Chapter 19, “Crystal Reports Tools,” discusses tools that help you with report design and application development.
Summary This chapter showed you how to install Crystal Reports and gave an overview of the rest of the book. Updates and corrections to this chapter can be found on Hentzenwerke’s web site, www.hentzenwerke.com. Click on “Catalog” and navigate to the page for this book.
16
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Chapter 2: Touring Crystal Reports
17
Chapter 2 Touring Crystal Reports Crystal Reports has many features to help you easily create powerful and full-featured reports. This chapter takes you on a tour of the Crystal Reports design environment.
Users have come to expect software to make things easier for them. Toolbars, wizards, menus, and other application tools help you with using the application. Crystal Reports is no different. When you first launch Crystal Reports or create a new report by selecting File | New from the menu or clicking the New button on the standard toolbar, the Crystal Report Gallery dialog box displays. Using the Crystal Report Gallery, you can open an existing report, create a new report using one of the report wizards, called Experts, or create a blank report.
Report Experts The Crystal Report Gallery shows four different report Experts: •
Standard
•
Cross-Tab
•
Mail Label
•
OLAP
These Experts walk you through a series of steps to select the data and format the report. The exact steps depend on the type of report you select. Most of the reports you create using the Report Expert will be standard reports. The Standard Expert is the one I have chosen to discuss here. Once you choose an Expert, click OK.
Data page The Data page is where you select the tables to include in the report. You can select an existing data connection, select items from the Repository, or create a new connection. The Repository is discussed in Chapter 5, “Intermediate Reporting.” Click Database, to display the Data Explorer. You will briefly see the data page in Chapter 3, “Creating Your First Report” and it is discussed more thoroughly in Chapter 4, “Accessing Data.” Once you select the data tables, click Close.
Links page If you choose multiple tables, Crystal Reports prompts you to link the tables using keys. Crystal Reports initially joins the tables of the first fields that exist in both tables. To change the link, click the link line and delete it, then drag the key field from the parent table and put it on the matching field in the child table. See chapter 4, “Accessing Data,” for more about Linking.
18
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Fields page Once you link the tables, use the Fields page to select the fields to appear in the Detail section on the report. You can use drag-and-drop to move a field from one list to the other or select the field and click Add, Add All, Remove, or Remove All. There are several options on this page. The Browse Data option displays the data for the selected field. Find locates a specific field in the Available Fields list. This is useful when you have many fields available.
Grouping page The Grouping page is where you add any grouping to the report. Use Groups to organize data in a logical way and provide totals for the group. You do not have to group fields selected on the Fields page. You can order each field you select for grouping in ascending or descending order. Groups are discussed in detail in Chapter 5, “Intermediate Reporting.”
Summaries page Groups are commonly used to generate a subtotal. That is the purpose of the Summary page. For each field you select for a group, the Total page allows you to select the field to subtotal and the type of calculation. For example, in a numeric field you can generate a sum, average, minimum, maximum, and several other summaries. You can also create a percentage of the grand total and optionally add grand totals to the report. More about Summaries can be found in Chapter 5, “Intermediate Reporting.”
Group Sorting page When you select a Top or Bottom N, the groups matching your criteria are sorted at the beginning of the report. One example of this powerful feature is being able to see the top salespeople or territories or the top selling brands or products.
Chart page Use the Chart page to add a chart to the report. I discuss charts in more detail in Chapter 5, “Intermediate Reporting.”
Record Selection page You can select a subset of the data by using the Select page. This page equates to the Where clause of a SQL Select statement. You may only want to see data for a particular state or date range. This page is where you can set up this option.
Template page Finally, Use the Template page to assign a preset design template to a report. When you select one of the templates, formatting is applied to the report objects. Crystal Reports 9 allows you to add your own custom templates. Chapter 5, “Intermediate Reporting,” discusses this further.
Chapter 2: Touring Crystal Reports
19
Blank reports The Crystal Report Gallery also has an option to create a blank report. When you select this option, you have to create the report from scratch and do all of the formatting yourself. Selecting As a blank report causes the Database Expert to display.
The Crystal Reports desktop When you launch Crystal Reports, you see the application divided into different areas: menus, toolbars, Field Explorer, Repository Explorer, Report Explorer, design surface, and status bar. The design surface further divides into the Design and Preview areas.
Menus The Crystal Reports menus make available most of the functionality of the product. Some features are only available from a context menu or from a dialog box. The menu options are: File •
New… — Creates a new report.
•
Open… — Displays a File Open window to open an existing report.
•
Close — Closes the current report.
•
Save — Saves the current report.
•
Save As… — Saves the current report using a different file name.
•
Save Data with Report — If selected, the data used for a report is saved in the .rpt file. I recommend you turn this option off.
•
Save Subreport As… — Saves the current subreport as a different file.
•
Print Preview — Previews the current report.
•
Print (Preview Sample, Printer) — Prints or exports the current report.
•
Printer Setup… — Displays a Printer Setup window.
•
Page Setup… — Displays a Page Setup window used to change the page margins.
•
Export… — Displays the Export window.
•
Send To (Mail Recipient, Exchange Folder) — Allows you to send a report via email.
•
Options… — Displays the Crystal Reports Options window (see “Setting options”
later in this chapter). •
Report Options… — Sets options for the current report (see “Setting options” later in
this chapter).
20
CrysDev: A Developer’s Guide to Integrating Crystal Reports •
Summary Info… — Displays the Document Properties window to enter the author name, a report description, and other information.
•
MRU — The Most Recently Used list of reports.
•
Exit — Exits Crystal Reports.
Edit •
Undo — Undoes the latest changes.
•
Redo — Reapplies the latest undo.
•
Cut — Cuts the selected object and places it on the clipboard.
•
Copy — Copies the selected object and places it on the clipboard.
•
Paste — Pastes the object on the clipboard into a report.
•
Paste Special — Pastes an OLE object on the clipboard into the report and creates a
link back to the owning application. •
Delete — Deletes the currently selected object.
•
Select All — Selects all the objects in a report.
•
Find… — Displays the Find window to locate a particular item in a report.
•
Go To Page — Displays the Go To Page dialog box. You can go to a specified page
or the first or last page in the preview. • •
Edit Report Object… — Displays a window for editing selected report object. Subreport Links… — Displays the Subreport Links window to link the parent report
to the subreport. •
Browse Field Data… — Displays a window showing data from a selected field.
•
Object — This menu item changes to match the selected object. Choose it to edit the
current object. •
Links… — Use to make changes to OLE links.
View •
Design — Sets the current view to the designer.
•
Preview — Sets Preview as the current view. This option is only available when the
preview is selected. •
Other Views — Lists any other views or drill-downs you have displayed. This option is only available when the view exists.
Chapter 2: Touring Crystal Reports •
21
Close Current View — Closes the current active view. You cannot close the Design
view. •
Field Explorer — Toggles the display of the Field Explorer.
•
Report Explorer — Toggles the display of the Report Explorer.
•
Repository Explorer — Toggles the display of the Repository Explorer.
•
Toolbars — Displays the Toolbars window for selecting the toolbars to display and
setting options for them. •
Status Bar — If selected, the status bar displays.
•
Group Tree — When selected, the group tree displays when in preview mode.
•
Zoom… — Displays the Magnification Factor window to increase or decrease the
view of the report. •
Rulers (Design, Preview) — Toggles the display of rulers in Design and Preview
views. •
Guidelines (Design, Preview) — Toggles display of guidelines in Design and Preview
views. •
Grid (Design, Preview) — Toggles display of the grid in Design and Preview views.
•
Tooltips (Design, Preview) — Toggles display of tooltips in Design and Preview
views. Insert •
Text Object — Inserts a text object into a report.
•
Summary… — Inserts a summary object into a report.
•
Field Heading — Inserts a new field heading for the selected field in the Designer.
This option is only available for fields that do not currently have a heading. •
Group… — Inserts a new group into a report.
•
OLAP Grid… — Inserts an OLAP cube into a report.
•
Cross-Tab… — Inserts a cross-tab into a report.
•
Subreport… — Inserts a subreport into a report.
•
Line — Inserts a line object into a report.
•
Box — Inserts a box into a report.
•
Picture… — Inserts a picture into a report.
•
Chart… — Displays the Chart Expert to insert a chart into a report.
22
CrysDev: A Developer’s Guide to Integrating Crystal Reports •
Map… — Display the Map Expert to insert a map into a report.
•
OLE Object… — Inserts an OLE object into a report.
•
Template Field Object — Inserts a template field into a report. Template fields are
useful for creating generic reports because they do not bind to any table or field. Chapter 6, “Advanced Reporting,” covers more about Template fields. Format •
Format Field – Displays the Format Editor window for the currently selected report
object. •
Hyperlink – Displays the Hyperlink page of the Format Editor window for the currently selected report object.
•
Use Expert – This option changes based on the object you have selected. If an Expert
is available for the object, this option will launch it. •
Highlighting Expert – Displays the Highlighting Expert window. The Highlighting Expert is discussed in Chapter 5, “Intermediate Reporting.”
•
Line Height… -- Allows you to set the measurements for how text is placed between
two lines on a report. This option is only available when you are not using free-form placement. •
Text Formatting… -- Displays the Text Format dialog box to format selected text.
•
Report Style Expert – Displays the Report Style Expert to format a report according to
a predefined style. •
Move (Backward, To Back, Forward, To Front) – Changes the location of a selected
item along the z-axis. •
Align (Tops, Middles, Bottoms, Baseline, Lefts, Centers, Rights, To Grid) – Aligns the
selected objects with the last item selected. •
Size (Same Height, Same Width, Same Size) – Sets the height and/or width of
selected objects to that of the object you selected last. •
Size and Position – Displays the Object Size and Position window to set the size and
location of a selected object. •
Pivot OLAP Grid – Rotates an OLAP grid.
•
Pivot Cross-Tab – Rotates a cross-tab.
Chapter 2: Touring Crystal Reports
23
Database •
Database Expert… -- Displays the Database Expert.
•
Set Datasource Location — Sets the location of a table.
•
Log On or Off Server — Use to log on or off the database or server.
•
Browse Data — Displays a browse window containing data for a selected field.
•
Set OLAP Cube Location — Sets the location of an OLAP cube.
•
Verify Database — Checks that the database is in the specified location and its structure has not changed.
•
Show SQL Query — Displays the SQL SELECT statement used to gather the data.
•
Perform Grouping on Server — Instructs Crystal Reports to do a GROUP BY on the
server instead of locally. •
Select Distinct Records — Adds a DISCTINCT clause to the SQL SELECT
command. Report • Select Expert — Displays the Select Expert to modify the SQL SELECT statement. •
Selection Formulas (Record, Group) — Displays the Formula Workshop to enter selection criteria formulas. See Chapter 8, “Using Formulas”.
•
Formula Workshop — Displays the Formula Workshop.
•
Alerts (Create or Modify Alerts, Triggered Alerts) — Creates or modifies an existing
alert or displays any triggered alerts. Alerts are discussed in Chapter 6, “Advanced Reporting.” •
Report Bursting Indexes — Displays the Saved Data Indexes window. These are indexes used with saved data to increase the reporting speed.
•
Section Expert — Displays the Section Expert.
•
Group Expert — Displays the Group Expert.
•
Group Sort Expert — Displays the Group Sort Expert.
•
Record Sort Expert — Displays the Record Sort Expert.
•
XML Expert — Displays the XML Expert.
•
Template Expert — Displays the Template Expert.
•
OLAP Report Settings — Displays the OLAP Report settings window. This option is
only available when you are using an OLAP cube.
24
CrysDev: A Developer’s Guide to Integrating Crystal Reports •
Hierarchical Grouping Options — Displays the Hierarchical Options window.
•
Refresh Report Data — Reloads the report data.
•
Set Print Date/Time — Allows you to specify the print date and time.
•
Performance Information — Displays the Performance Information window.
Window •
Tile Vertically — Vertically tiles all open reports.
•
Tile Horizontally — Horizontally tiles all open reports.
•
Cascade — Cascades all open reports.
•
Arrange Icons — Arranges all minimized report windows at the bottom of the Crystal
Reports window. •
Close All — Closes all open reports.
•
Open Windows List —Lists each open report window.
Help •
Crystal Reports Help — Opens the main Crystal Reports Help file.
•
Context Help — Activates What’s This? Help.
•
Welcome Dialog — Displays the Welcome to Crystal Reports window.
•
Additional Help Files — Lists additional Help files available on the Crystal
Reports CD. •
Crystal Decisions On the Web — Provides several links to different Crystal Decisions
web sites. •
Web Report Samples — Lists web report sample files.
•
Register / Change Address — Displays the Software Registration Wizard.
•
About Crystal Reports — Displays the About window.
Chapter 2: Touring Crystal Reports
25
Toolbars Crystal Reports has four toolbars: Standard, Formatting, Insert Tools, and Expert Tools. You can float each toolbar or dock to the top, left, bottom, or right edges of the screen. In addition, select View | Toolbars from the menu to display the Toolbars dialog box. This is where you show or hide each toolbar and select using large buttons and tooltips. The Standard toolbar The Standard toolbar (see Figure 1) contains most of the functionality you will use when designing reports. The controls on this toolbar, from left to right, are:
Figure 1. The Standard Toolbar contains most of the functions you need. •
New — Creates a new report.
•
Open — Displays a file open dialog to open an existing report.
•
Save — Saves the current report.
•
Print — Prints the current report.
•
Print Preview — Previews the current report.
•
Export — Exports the current report.
•
Refresh — Reloads the report data.
•
Cut — Cuts the selected object and places it on the clipboard.
•
Copy — Copies the selected object and places it on the clipboard.
•
Paste — Pastes the object on the clipboard into the report.
•
Undo — Undoes the latest changes.
•
Redo — Reapplies the latest undo.
•
Toggle Group Tree — Toggles the display of the Group Tree when previewing.
•
Field Explorer — Toggles the display of the Field Explorer.
•
Report Explorer — Toggles the display of the Report Explorer.
•
Repository Explorer — Toggles the display of the Repository Explorer.
•
Find — Finds the specified report object or data item in preview.
•
Zoom Control — Specifies the zoom percentage.
•
Help — Toggles What’s This? Help.
26
CrysDev: A Developer’s Guide to Integrating Crystal Reports
The Formatting toolbar The Formatting toolbar (see Figure 2) is used to set formatting for a selected object. The controls on this toolbar, from left to right, are:
Figure 2. Use the Formatting toolbar to apply formatting to various report objects. •
Font Face — Changes the font for the selected object.
•
Font Size — Changes the font size of the selected object.
•
Increase Font Size — Increases the font size of the selected object.
•
Decrease Font Size — Decreases the font size of the selected object.
•
Bold — Toggles bold font for the selected object.
•
Italics — Toggles italic font for the selected object.
•
Underline — Toggles underline for the selected object.
•
Align Left — Aligns the text of the object with the left-hand border of the object.
•
Align Center — Aligns the text of the object in the horizontal center of the object.
•
Align Right — Aligns the text of the object with the right-hand border of the object.
•
Justify — Justifies the text of the selected object.
•
Font Color — Displays a color picker to change the text color of the selected object.
•
Outside Borders — Allows you to set any borders you want on the selected object.
•
Suppress — Suppresses the selected object.
•
Lock Format — Toggles the format lock for the current object. When the lock is
active, you cannot change the formatting of the object. •
Lock Size/Position — Toggles the size and position lock for the current object. When
the lock is active, you cannot change the size or position of the object. •
Currency — Toggles printing of the currency symbol for the selected object.
•
Thousands — Toggles printing of the thousands separator for the selected object.
•
Percent — Toggles printing the percent sign for the selected object.
•
Increase Decimals — Increases the number decimal positions for the selected object.
•
Decrease Decimals — Decreases the number of decimal positions for the
selected object.
Chapter 2: Touring Crystal Reports
27
The Insert Tools toolbar The Insert Tools toolbar (see Figure 3) contains functionality that lets you quickly insert a new object into the report. The buttons on the toolbar, from left to right, are:
Figure 3. Use the Insert Tools toolbar to insert new objects. •
Insert Text Object — Adds a new text object to the report.
•
Insert Group — Adds a new group to the report.
•
Insert Summary — Adds a new summary to the report.
•
Insert Cross-tab — Inserts a new cross-tab object.
•
Insert OLAP Grid — Adds an OLAP grid to the report.
•
Insert Subreport — Inserts a subreport.
•
Insert Line — Inserts a line.
•
Insert Box — Adds a box to the report.
•
Insert Picture — Adds a new picture.
•
Insert Chart — Adds a chart to the current report.
•
Insert Map — Inserts a map.
The Expert Tools toolbar The Expert Tools toolbar (see Figure 4) allows you to quickly display a specific Expert. The buttons on this toolbar, from left to right, are:
Figure 4. The Expert Tools toolbar. •
Database Expert — Displays the Database Expert.
•
Group Expert — Displays the Group Expert.
•
Group Sort Expert — Displays the Group Sort Expert.
•
Record Sort Expert — Displays the Record Sort Expert.
28
CrysDev: A Developer’s Guide to Integrating Crystal Reports •
Select Expert — Displays the Select Expert.
•
Section Expert — Displays the Section Expert.
•
Formula Workshop — Displays the Formula Workshop.
•
OLAP Report Settings — Displays the OLAP grid settings dialog.
•
Template Expert — Displays the Template Expert.
•
Format — Displays the Format dialog for the currently selected object.
•
Insert Hyperlink — Displays the Hyperlink page of the Format dialog for the currently
selected object. •
Highlighting — Displays the Highlighting Expert for the currently selected report
object.
Status bar The status bar displays (see Figure 5) at the bottom of the Crystal Reports window. You toggle the display of the status bar by selecting View | Status Bar from the menu. The status bar provides useful information. At the left is detailed information about the selected object or the highlighted menu item. Figure 5. The Status bar provides information about the currently selected object. Next it displays the location and size of the selected item. For example, you may see something like 0.2, 0.9 : 3.3 x 0.2. This tells you the current object is at 0.2 inches on the xaxis and 0.9 inches on the y-axis in the current section. The next set of numbers tells you how big the object is, 3.3 inches horizontally by 0.2 inches vertically. The last two pieces of information only show up when previewing the report. First is the number of records processed and finally the percent of record processing that is complete. If you have a large data set to report or if the SELECT statement takes a long time to complete, you will see these numbers change as the data processes.
Design page The Design page (see Figure 6) is where you do all of your work. On the left side is the section identification area. This shows you the name of each section. You can right-click this area to display a shortcut menu with different options for the sections. The rulers are at the top and left of the actual design area. Select View | Rulers from the menu to toggle the display of the rulers. The rest of the design page is the actual report. You place different report objects in the specific sections to create the report. The controls at the top, right are not enabled in the Designer.
Chapter 2: Touring Crystal Reports
29
Figure 6. The Designer is where you do all of your work.
Preview page Select File | Print Preview or click the Print Preview button on the Standard toolbar to display the Preview page (see Figure 7). This is a fairly accurate display of what the printed report will look like. You can also do some report design on the Preview page. At the far left of the Preview is the Group Tree. You click one of the listed items to jump directly to that item in the preview. Select View | Group Tree from the menu to toggle the display of the Group Tree. Next is the section identification area. Just like on the Design tab, right-click to display a shortcut menu for changing section information. Rulers are at the immediate left and top of the actual preview area. You toggle the display of the rulers by selecting View | Rulers from the menu. The controls at the top, right are available in Preview mode. First is the print date and time, followed by the navigation controls to move from page to page in the report. The current page and total number of pages also displays.
30
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 7. The Preview shows what the report will look like when printed. On the left is the Group Tree you can use to navigate quickly to a specific group.
Report Sections Crystal Reports divides the report into several areas: report header, page header, group header, detail, group footer, page footer, and report footer. Each report is limited to one report header, page header, detail, page footer, and report footer area. You can have multiple group header and footer areas. Each area further divides into sections. For example, you can have multiple detail sections or multiple page header sections. When you place fields, text, and other objects on the report, you place them in a section. You can format and control each section individually.
Section Expert You use the Section Expert to change settings for a particular section. For example, you can change the position of a particular section, set its background color, or programmatically control how different items work. Throughout the rest of this chapter, you will see several dialog boxes. I will not explain each option, but only discuss some of the more interesting or confusing items. The first dialog box is the Section Expert (see Figure 8).
Chapter 2: Touring Crystal Reports
31
Figure 8. You use the Section Expert to customize a particular report section. The first item of interest on the Section Expert is the formula button. It looks like an equation with a pencil. When you click a formula button, the Formula Editor displays for you to enter a programmatic expression to control a particular feature. Formulas are discussed in detail in Chapter 8, “Using Formulas.” Once you enter a formula behind a specific button, the color of the equation text on the button changes from blue to red and the pencil stands at an angle, instead of lying down. You will see the formula buttons in several dialog boxes. The Hide (Drill-Down OK) option suppresses the section from displaying in the Group Tree. However, you can still double-click a group on the Preview page to drill down to the detail for the particular item. To hide a section completely in the report, select the Suppress (No Drill-Down) option. Widow/orphan control is accomplished with the Keep Together option. When you select this option, Crystal Reports attempts to print the entire section on one page. Choosing Underlay Following Sections will cause the selected section to print behind sections that follow it. This is useful for adding watermarks to a report. Simply add a new section near the top of the report, place the graphic in the section, and then select this option.
Formatting report objects Crystal Reports provides many formatting capabilities. The easiest way to format an object is using the Formatting toolbar. However, this toolbar only offers a subset of the format capabilities. Use the Format Editor to access all the formatting options. There are several ways to display the Format Editor:
32
CrysDev: A Developer’s Guide to Integrating Crystal Reports •
Right-click an object and select Format Field from the shortcut menu.
•
Select Format | Format Field from the menu.
•
Click the Format button on the Supplementary toolbar.
Note that the pages on the Format Editor change depending on the object type and the data type of the field. The example shown here is for a regular field containing character data.
Common page The Common page (see Figure 9) has settings for adjusting the position and size of an object. Check Suppress to hide the object so it doesn’t print. To enable widow and orphan control, select Keep Together. You can also rotate the object either 90 or 270 degrees.
Figure 9. Use the Common page of the Format Editor to specify the location and printing of a particular object.
Chapter 2: Touring Crystal Reports
33
Border page The Border page (see Figure 10) is used to set the borders and background color of the object. The border on each side of an object can be set and you can use a different line type on each. If you set the bottom border, the entire width of the object appears underlined, as opposed to selecting the underline attribute of the font, which only underlines the actual text in the object. Use the Tight Horizontal setting to change the length of the horizontal border. If not selected, the length of the horizontal border is the same for each item; in other words, the length of the actual report object. If you select Tight Horizontal, the length of the border changes for each record and is the same length as the actual text.
Figure 10. Use the Border page of the Format Editor to change border settings for a selected object.
34
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Font page The Font page (see Figure 11) is used to set the font for an object. The only item of interest is Character Spacing Exactly. When you select this option, the width of each character is the number of points you specify. The actual width of the printed font does not change, but rather the spacing between characters changes so the space used by each character is exactly what you specify. For example, if you use a 12-point font and set character spacing to 14 points, each character will be 12 points high and 14 points wide.
Figure 11. You can specify the font settings of a selected object on the Font page of the Format Editor.
Chapter 2: Touring Crystal Reports
35
Paragraph page Paragraph formatting affects the way text prints inside the report object. There are two items of interest on the Paragraph page (see Figure 12). The first is Line Spacing. You can set the line spacing as an exact number of points or as a multiple of the font size. The other interesting item is Text Interpretation. There are three settings; none, RTF Text, and HTML Text. This setting tells Crystal Reports how to interpret data saved in a character or memo field. If you set the option as HTML Text, Crystal Reports interprets the data as HTML. This adds powerful formatting options to the report.
Figure 12. The Paragraph Formatting page of the Format Editor is where you change settings for how text prints inside a selected object.
36
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Hyperlink page Finally, the Hyperlink page (see Figure 13) tells Crystal Reports an object is a hyperlink. When the user clicks the object in the Preview, the hyperlink launches.
Figure 13. You create hyperlinks in the report from the Hyperlink page of the Format Editor.
Resizing and moving objects When you drop report objects onto the designer, it’s quite rare when the object ends up in the exact spot or the exact size you want it. This requires you move and resize the object. You can do this with the mouse, keyboard, the Object Size and Positioning dialog box, or by using guidelines.
Chapter 2: Touring Crystal Reports
37
Using the mouse The mouse is the most obvious way to change the location or size of an object. Simply drag the object to the desired location to move it or grab the handles on the sides of the selected object to resize it.
Using the keyboard The cursor keys on the keyboard provide another method to move or resize an object. Simply press a cursor key and the object moves in the desired direction. Use the Shift key in combination with the cursor key to resize the object.
The Object Size and Position window The Object Size and Position (see Figure 14) dialog box provides precise location and size abilities. Select Format | Size and Position from the menu to display the dialog box. The Xaxis position is relative to the left margin of the report. The Y-axis position is relative to the top of the section.
Figure 14. The Object Size and Position dialog box allows precise placement and sizing of a report object.
Guidelines Guidelines let you align the border of multiple objects and change them all at the same time. Small triangles (see Figure 15) on the rulers indicate the location of the guidelines. Select View | Guidelines Design or View | Guidelines from the menu in Preview view to toggle display of guidelines as dashed horizontal and vertical lines on the Design and Preview pages. When you lock the border of an object to a particular guideline, the border moves when you move the guideline. To add a new guideline, click the ruler where you want the guideline to be. You may have to move or resize the report object to get it to lock to the guideline. To remove a guideline, click the triangle and drag it off the ruler.
38
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 15. Use guidelines to align and move report objects.
Setting options Crystal Reports offers many options that affect how the software functions or affect the current report. Application options affect each report you design while report options affect only the current report.
Application options Application options affect how Crystal Reports functions or looks. Select File | Options from the menu to display the Options dialog box, where you set these options. In my opinion, the settings on the dialog box are not well organized. For example, there are several pages where you can change settings that affect how Crystal Reports works with data. Instead of centralizing these settings, they are spread across several pages. Layout page The first page of the Options dialog box is the Layout page (see Figure 16). The first interesting option is Insert Detail Field Headings. When you select this option, column headings are placed in the page header when you drop a field onto the details section of the report. Free-Form Placement means when you place an object on the report, it does not have to be placed in a grid.
Chapter 2: Touring Crystal Reports
39
Figure 16. Use the Layout page of the Options dialog box to specify default settings for Crystal Reports. Database page The Database page (see Figure 17) affects how Crystal Reports connects to databases and shows database objects. The Use Indexes or Server for Speed option tells Crystal Reports to use any index files that are associated with the database. Checking this option causes the record selection to perform faster.
40
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 17. Use the Database page of the Options dialog box to change settings for how Crystal Reports interacts with different databases. When selected, the Perform Query Asynchronously option tells Crystal Reports to start loading data into the report before the query completes. This allows you to start producing the report more quickly when a large data set is returned. It also lets you cancel an executing query.
Chapter 2: Touring Crystal Reports
41
Editors page There isn’t much of interest on the Editors page (see Figure 18). The settings on this page affect the visual appearance of different items in the Formula Editor.
Figure 18. You change editor settings on the Editors page of the Options dialog box. Data Source Defaults page One of the settings you can change on the Data Source Defaults page (see Figure 19) is the type of native access database files Crystal Reports displays by default. You can set the directory location and the file extensions for both the data and index files.
42
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 19. The Data Source Defaults page of the Options dialog box is where you change settings for native data types and dictionary locations. Reporting Several options are available on the Reporting page (see Figure 20). The most important of these is Save Data With Report. When selected, any data used to design the report saves with the report. This makes the RPT file bigger and requires you to refresh the data each time you run the report. Update Connected Repository Objects When Loading Reports causes any Repository objects used in the report to be updated with the latest object stored in the Repository. The Repository is a new feature in Crystal Reports 9 and is discussed in Chapter 5, “Intermediate Reporting.”
Chapter 2: Touring Crystal Reports
43
Figure 20. Use the Reporting page of the Options dialog box to change default settings for converting data and saving a report file. You can enter Crystal Reports formulas in Crystal or BASIC syntax. You can change the default syntax to use with the Formula Language setting. Formulas are covered in detail in Chapter 8, “Using Formulas.” Fields There isn’t much to say about the Fields page (see Figure 21). When you click one of the buttons, the Format Editor for the particular data type displays.
44
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 21. Selecting a Field format item from the Fields page of the Options dialog box displays the appropriate page of the Format Editor. Use this to change default settings for how a particular data type prints. Fonts The Fonts page (see Figure 22) allows you to select default fonts for the different types of fields. When you select one of the field type buttons, the Font dialog box displays so you can set the default font for the field.
Chapter 2: Touring Crystal Reports
Figure 22. You change default font settings for different items on the Fonts page of the Options dialog box. Smart Tag The Smart Tag options (see Figure 23) are used to define web server and page information when you use Microsoft Office smart tags attached to Crystal Reports objects.
45
46
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 23. Set the Smart Tag options for linking to Microsoft Office XP Smart Tags.
Report options In addition to application-wide settings, you can change how Crystal Reports works with the current report. Select File | Report Options to display the Report Options dialog box (see Figure 24). All the settings in this window are also available in the Options dialog box. Again, I recommend Save Data With Report not be selected. By default, this option is selected.
Chapter 2: Touring Crystal Reports
47
Figure 24. Change settings for the current report in the Report Options dialog box. Report Parts are portions of a report displayed alone without the rest of the report. Using the Report Options dialog box, you can define the name of the home object and the specific records to use in the home object. Chapter 16, “Web Reporting,” discusses Report Parts in more detail.
The report-processing model Before moving on to report design, it’s important to understand how Crystal Reports processes a report. Crystal Reports is a multi-pass report designer. This means the report processes several times. Each pass processes different pieces of information. Crystal Reports actually makes three passes though the report or data.
48
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Pre-pass 1 Before looking at any data, Crystal Reports processes any constant formulas. These are formulas that have the same value throughout the entire reporting process. This pass is also called BeforeReadingRecords.
Pass 1 During the first pass, the following things occur: •
Records are read from the database. The data is stored in memory or temporary tables and is not read again.
•
Formulas that contain references to data fields, but are not used for subtotals or summaries are evaluated. This process is called WhileReadingRecords.
•
Records are sorted and grouped.
•
Subtotals and summaries are calculated.
•
Cross-tabs are generated.
Pre-pass 2 Groups are ordered for Top/Bottom N and Hierarchical grouping.
Pass 2 Page formatting occurs in pass 2. Crystal Reports does page formatting on demand, meaning the page is not formatted until needed. The following things occur in this pass: •
Group selection formulas are calculated.
•
Running totals are calculated.
•
Formulas marked as WhilePrintingRecords are calculated. These are formulas used to calculate subtotals and summaries.
•
Charts and maps are processed.
•
Subreports are processed.
Pass 3 In the final pass, the total page count is calculated.
Summary You should now be familiar with how Crystal Reports is arranged, how to set the many available options, and how a report is processed. In subsequent chapters, you will see many more dialog boxes and settings as you learn more about the report design process.
Chapter 2: Touring Crystal Reports Updates and corrections to this chapter can be found on Hentzenwerke’s web site, www.hentzenwerke.com. Click “Catalog” and navigate to the page for this book.
49
50
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Chapter 3: Creating Your First Report
51
Chapter 3 Creating Your First Report Creating reports that include drill-down and graphing in Crystal Reports is easier than you might think. This chapter will help you understand the basics of report design with Crystal Reports.
You are finished installing Crystal Reports and are ready to create your first report. You launch the application and see a dialog box asking you to create a report using either the Report Wizard or a Blank Report. WOW, a wizard! It must know a lot about reports. So, you select that option and are led on your way to creating a wonderful report. However, you soon find the Report Wizard doesn’t provide the control you need. It gives you some default settings, many of which you don’t like. It’s also not good at helping with existing reports. Maybe it would have been better to select Blank Report. That is exactly what this chapter is about, creating a report from scratch. You won’t spend a lot of time on formatting and getting the report to look perfect. The Crystal Reports documentation, help files, and other books do a good job with this. However, I think it is important to give you some reporting basics before diving into programmatically controlling Crystal Reports.
Designing the report Before sitting down with Crystal Reports, you should have an idea of what the finished report should look like. This report will be a sales listing by genre and title for the fictional company WebNet Video. I start by listing the report items, sketching the report layout on paper, and then look at the tables you need for the report.
Sketching the report I already gave you some information about the report, sales listing by genre and title. This sounds like a good report title. The title gives you a clue that you need genre and sales information. The report should list each sale, subtotal the quantity ordered and total dollar value by title and genre, and have a grand total for each grouping at the end, along with a pie chart comparing the subtotal sales for each genre. Most reports also include the print date and page number. Finally, the company logo should also be included. Table 1 lists the items to include.
52
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Table 1. Items needed for the Sales Listing by Genre and Title report. Item
Report Location
Title, “Sales by Genre and Title” Logo Print date Page number Genre Movie title Customer First name Customer Last name Customer city Customer state Quantity purchased Purchase price Extended price (quantity * price) Total by title Total by genre Grand Total Pie chart
Page Header Page Header Page Header Page Header Group 1 Header Group 2 Header Detail Detail Detail Detail Detail Detail Detail Group 2 Footer Group 1 Footer Report Footer Report Footer
Now that all the report elements are listed, it’s time to lay out the different elements. It is easier to sketch the report with each element and its location defined. Figure 1 shows the layout for the report.
Figure 1. Sketching the report layout makes report design easier.
Chapter 3: Creating Your First Report
53
The report data This report will use FoxPro 2.6 DBF files. Crystal Reports can natively read these files, so there is no need to setup ODBC drivers or an OLE DB connection. Chapter 4, “Accessing Data,” presents a detailed discussion of using a variety of data sources with Crystal Reports. Table 2 describes the four data tables you will use in the report. Table 2. Descriptions of the report data tables. Table
Description
Movies
Information for each movie available for purchase Customer information Order header Order detail
Customer OrdHd OrdDet
Your first report, step-by-step Now that you have a good idea of how the report should look, I’ll walk you through the report design process step-by-step. 1.
Launch Crystal Reports.
2.
If the Welcome to Crystal Reports dialog box displays (see Figure 2), select As a Blank Report, click OK, and then skip to step four. If the Welcome dialog box does not display, proceed to step three.
Figure 2. The Welcome to Crystal Reports dialog displays when you launch Crystal Reports if “Show welcome dialog at startup” is selected.
54
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Selecting the data source Now that you have selected the type of report you want to create, the next step is to identify the data sources. Use the Database Expert dialog box (see Figure 3) to select the data sources for your report.
Figure 3. Use the Database Expert to select the data source. 3.
Expand the tree view under Create a Connection, and then under xBase.
4.
Navigate to the file Movies.DBF and click Open in the Open window to select it.
These files, as well as the completed report, are available for download from the Hentzenwerke website. 5.
Back in the Database Expert, double-click Find Database File to select another table.
6.
Now repeat steps four and five for OrdDet.DBF, OrdHd.DBF, and Customer.DBF. Once you select all the files, click Close.
7.
You have selected the tables to use in the report, but Crystal Reports is not yet using the tables. Select customer.dbf in the Available Data Sources list and click the Move button to move it to the Selected Tables list. You can optionally dragand-drop the table.
8.
Repeat step seven for the three other tables.
9.
Click the Links tab on the Database Expert to display the Links page.
Chapter 3: Creating Your First Report
55
10. The Links page (see Figure 4) is where you link the tables together. In our example, the tables are linked properly to create a parent-child relation from Movies to OrdDet. When you do this, the arrows may point backwards, but you get the same linking. Click OK to close the dialog box.
Figure 4. Use the Links page of the Database Expert to connect related tables. 11. You may get a warning (see Figure 5). If you do, click OK to dismiss it.
Figure 5. The Database Warning reminds you about adding additional data components to the report.
Adding data fields to the report Now it’s time to start placing objects on the report. I’ll start with fields from the data tables. Figure 6 shows the Crystal Reports design surface. It is here you’ll do most of your work. Chapter 2, “Touring Crystal Reports,” discusses the designer in more detail, including explanation of the menus, toolbars, toolboxes, and different report bands.
56
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 6. Use the Crystal Reports design surface to create a report. 12. In the Field Explorer (see Figure 7), drill down to the Customer table and drag the field FirstName onto the Details band of the report.
Chapter 3: Creating Your First Report
57
Figure 7. The Field Explorer displays the fields for each table added to the report. 13. Grab the right side of the FirstName field in the Detail band and drag to the left to make the field width shorter. The column label in the Page Header band resizes automatically. 14. Drag the Customer.LastName, Customer.City, Customer.State, OrdDet.Quantity, and OrdDet.UnitPrice fields onto the Details band, resizing each field as needed. Your report should now look like Figure 8.
58
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 8. The Design tab shows the added fields from the data tables.
Adding a calculated field Crystal Reports has very powerful capabilities for calculated fields, called formula fields. I will explain formula fields in detail in chapter 8, “Using Formulas”. For now, enter a simple formula to calculate the total price for each detail line. 15. Add a total field for each detail item. Click “Formula Field,” and then click the New button in the Field Explorer (see Figure 9).
Chapter 3: Creating Your First Report
59
Figure 9. Create a new Formula Field in the Field Explorer. 16. Enter “DetailTotal” for the Name (see Figure 10), and then click Use Editor.
Figure 10. Name the new Formula Field. 17. Use the Formula Editor (see Figure 11) to create and edit formula fields. Chapter 8, “Using Formulas,” explains formulas in detail. For now, enter {orddet.QUANTITY}*{orddet.UNITPRICE} in the lower right of the Formula Editor window.
60
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 11. Use the Formula Editor to create formula fields. 18. Close the Formula Editor and answer Yes when it prompts you to save changes. 19. Drag the DetailTotal field from the Field Explorer onto the Details band of the report. Place this new field to the right of the existing Details band fields.
Grouping and group totals The report layout required grouping by genre and title along with totals for each group. Adding groups and totals is easy in Crystal Reports. 20. Select Insert | Group from the menu. In the Insert Group window (see Figure 12), select Movies.Genre in the top drop-down list for the grouping. Click OK to add the group to the report.
Chapter 3: Creating Your First Report
61
Figure 12. Define a grouping in the Insert Group dialog box. 21. Click Quantity in the Details band. Select Insert | Summary to display the Insert Summary dialog box (see Figure 13). 22. Select “Group #1: movies.GENRE – A” for the Summary Location. Click OK to add the subtotal to Group Footer #1.
62
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 13. Use the Insert Subtotal dialog box to add grouping subtotals to the report. 23. Again, click Quantity on the Details band. Select Insert | Summary. Verify that Summary Location is set to “Grand Total (Report Footer),” and then click OK to add the grand total to Report Footer band (see Figure 14).
Chapter 3: Creating Your First Report
63
Figure 14. Use the Insert Summary dialog box to define grand totals for a report. 24. Add a new group of Movies.Title to the report. Crystal Reports creates Group #2. 25. Add a Quantity subtotal to the Group Footer #2 (Movies.Title). 26. Click the @DetailTotal field in the Details band and add a new subtotal for each group and a grand total in the Report Footer. 27. This is a good place to view the report. Select File | Print Preview (see Figure 15).
64
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 15. The Print Preview shows how the printed report will look. 28. Examine the preview. The Group Tree, just to the left of the report, lists each genre. As you select an item in the Group Tree, Crystal Reports displays the details for that item. In Chapter 12, “Previewing the Report at Runtime,” you will his drill-down capability is available to end users. Note the Quantity subtotals and grand total are formatted incorrectly. They shouldn’t have decimals. Also, the column headings are not correct.
Formatting the report Crystal Reports offers powerful formatting features through the Format Editor. 29. Select the Design tab to go back to the Designer. Right-click the Quantity field in the Group Footer #2 band and select Format Field from the shortcut menu. 30. Select -1,123 for the field format on the Number tab in the Format Editor (see Figure 16). Click OK to save the format.
Chapter 3: Creating Your First Report
65
Figure 16. Select the field format in the Format Editor. 31. Change the format for the Quantity subtotals Group Footer #1 and for the grand total in the Report Footer band. 32. Double-click FIRSTNAME in the Page Header. Delete the text and enter “First Name” for the column heading. Change the column headings for the other fields to “Last Name,” “City,” “State,” “Qty,” “Price,” and “Total.”
66
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Adding the page header The page header prints at the top of each page. You can use text, data, formula fields, or even graphics in any band of the report, including the page header. 33. Drag the splitter bar between the Page Header and Group Header #1 bands down to enlarge the Page Header band. Make it about 1 ½” tall. 34. Drag each column header down so it is at the bottom of the Page Header band. 35. Insert the report title. Select Insert | Text Object from the menu. Drag the new text object so it centers horizontally at the top of the Page Header band. 36. Using the toolbar, set the font to 14-points and bold. 37. Enter the report title “Sales by Genre and Title,” and then resize the text field so the entire report title is visible. 38. In the Field Explorer, drill down in Special Fields, drag “Page N of M” onto the Page Header band, and place it below the report title. 39. Right-click “Page N of M” in the Page Header band and select Format Field from the shortcut menu. 40. On the Common tab of the Format Editor (see Figure 17), set the Horizontal Alignment to “Centered” and click OK to save the format settings.
Chapter 3: Creating Your First Report
67
Figure 17. Use the Common tab of the Format Editor to set common field formatting options. 41. Drag “Print Date” from the Field Explorer and put it below “Page N of M” on the Page Header band. 42. Add the company logo. Select Insert | Picture and choose the file WebNet.JPG. Place the logo in the upper left corner of the Page Header. 43. Now preview the report. Notice the page header fields do not align horizontally. Crystal Reports does not provide an easy way to center text horizontally on a page, but fear not! I’m about to show you how to do it.
68
CrysDev: A Developer’s Guide to Integrating Crystal Reports 44. On the Design tab, resize the report header field (Sales by Genre and Title) so it stretches horizontally across the entire report. Then, use the Format Editor to center the text in the field (for the text object, it’s on the Paragraph tab). Do the same with the page number and print date.
Charting made easy All that is left is to add the graph. Robust charting capabilities are one of the compelling features of Crystal Reports. You can easily add one or more charts from dozens of different types. 45. From the main menu, select Insert | Chart. On the Type tab of the Chart Expert (see Figure 18), set the chart type to Pie.
Figure 18. Choose the chart type in the Chart Expert dialog box. 46. Select the Data tab of the Chart Expert (see Figure 19). Set the Placement “Once per report” in the Footer. Also verify On change of is set to “Movies.Genre” and Show to “Sum of OrdDet.Quantity”.
Chapter 3: Creating Your First Report
Figure 19. Set the location and grouping of the chart on the Data tab. 47. Click OK to insert the chart into the Report Footer (see Figure 20). The graph does not display properly in the Designer. Crystal Reports only inserts a placeholder to show you where the chart will be.
69
70
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 20. The Designer only shows a placeholder for the chart. 48. Switch to the Preview tab and navigate to the last page of the report. Here the graph displays properly (see Figure 21).
Figure 21. Preview mode correctly shows the chart.
Chapter 3: Creating Your First Report
71
49. Double-click the Drama section of the pie. Crystal Reports drills down to the details for Drama (see Figure 22).
Figure 22. Double-click a pie section to drill down to the details for that slice. 50. To print the report, select File | Print | Printer, and then click OK. 51. You can export the report to a variety of different formats, including Word, Excel, and PDF. Select File | Print | Export and choose the format you want. If you select a file, it will prompt you to enter the file name. Chapter 14, “Exporting Reports,” discusses the various export options in detail. 52. Save the report. Select File | Save. Enter the file name “Sales by Genre”. Crystal Reports appends an RPT extension. Congratulations! You just created your first report using Crystal Reports.
Summary This chapter shows you how to create a fairly simple report. I also show you how to easily add graphs, totals, and drill-down capabilities. Some other concepts, such as file linking, formatting, and alignment are also presented. In other chapters, I show you how to give these capabilities to end users using the Crystal Reports runtimes.
72
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Updates and corrections to this chapter can be found on Hentzenwerke’s web site, www.hentzenwerke.com. Click “Catalog” and navigate to the page for this book.
Chapter 4: Accessing Data
73
Chapter 4 Accessing Data The entire purpose of reporting is to make sense of data. Therefore, it is important to know how to access data locked away in the database. In this chapter, you will learn how to pull data from multiple sources.
Crystal Reports has long had a reputation of being able to use just about any data source. If the database has an ODBC driver or an OLE DB Provider, it would almost guarantee that Crystal Reports could extract data for the report. Crystal Reports 9 made several improvements in data access, all of which make data access easier. The Database Expert is completely redesigned. The Visual Linking Expert has been replaced with an easier to use tool. SQL commands and the Crystal Repository replaced the old Crystal Dictionaries and Crystal.
Using the Database Expert The Database Expert (see Figure 1) is used to select the tables for a report. When you create a new report, the Database Expert displays in the first step. You can also select Database | Database Expert from the menu to display the Database Expert. The Database Expert lists data in five different categories as follows: •
Current Connections – Lists database objects already used in a report.
•
Repository – Lists objects stored in the Repository, discussed later in this chapter.
•
Favorites – Lists commonly used database objects.
•
History – Lists recently used database objects.
•
Create a New Connection – Used to create a connection to a new database object.
A database object is a field, view, cursor, stored procedure, or other object in a database usable as a data source for a report field. To add a database object to a report, move it from the Available Data Sources list to the Selected Tables list. Once you select two tables, the Links tab is added to the Database Expert (see the “Linking Tables” section later in this chapter).
74
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 1. Use the Database Expert window to select the tables for a report.
Creating a new connection When you add a new connection, you first need to expand the Create New Connection branch under Available Data Sources (see Figure 2). The data sources listed depend on which data components you installed with Crystal Reports. The steps to add a connection varies with the data source you select. I explain some of the connection options here. You can find a discussion of COM Connectivity in Chapter 15, “Integrating COM Components,” and ADO .NET in Chapter 17, “Crystal Reports .NET.”
Chapter 4: Accessing Data
75
Figure 2. You need to expand the Create New Connection branch to add new tables to a report. Access/Excel (DAO) When you select the Access/Excel (DAO) option a dialog box displays that allows you to enter the file information (see Figure 3). While called Access/Excel (DAO), this option also lets you connect to data other than Access or Excel files. You can select Access, Dbase, Excel, HTML, Lotus, Paradox, and text files or what Crystal Reports calls “direct access data”. This means Crystal Reports can natively access the data without using any external drivers.
76
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 3. Use the Access/Excel (DAO) window to enter information about direct access data sources. If the data source is password protected, make sure you select the Secure Logon check box and enter the log on information. Once you populate the necessary fields, click Finish to return to the Database Expert. ADO .NET (XML) Crystal Reports supports connecting to XML files, but don’t let this option fool you. You do not need ADO .NET (see Chapter 17, “Crystal Reports .NET”, for a complete discussion of Crystal Reports .NET) to connect to XML. Select this option to specify the file location (see Figure 4).
Chapter 4: Accessing Data
77
Figure 4. Use the ADO.NET (XML) dialog box to specify an XML file for the report data source. When you enter the XML File Path, you can use either a file name or a URL. The Visual Studio Data Class fields are explained in Chapter 17, “Crystal Reports .NET.” ODBC (RDO) Crystal Reports relies on an existing Data Source Name (DSN) to connect to a database using ODBC. When you select ODBC as a data source, Crystal Reports displays the ODBC (RDO) dialog box (see Figure 5). You can optionally select a File DSN. Once you select the DSN, Crystal Reports displays a second dialog box for you to enter the logon information for the database. Figure 6 shows this dialog box for the Northwind database in Microsoft SQL Server. Some databases, such as Visual FoxPro, do not support logons. The second page of the dialog box still displays. Just leave the fields empty and Crystal Reports connects to the data. When you enter all the logon information, click Finish to return to the Database Expert.
78
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 5. Use the Data Source Selection page of the ODBC (RDO) dialog box to select an ODBC data source.
Chapter 4: Accessing Data
79
Figure 6. The Connection Information page of the ODBC (RDO) dialog box is where you enter logon information for the database. OLAP Crystal Reports can connect to various OLAP servers and databases, including Microsoft SQL Server OLAP Services (Analysis Services), IBM DB2, Hyperion Essbase, and Crystal Analysis. When you choose to connect to an OLAP server, the Crystal OLAP Connection Browser displays (see Figure 7).
80
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 7. You select an existing OLAP server from the Crystal OLAP Connection Browser dialog box. Choose an OLAP server from the list or click Add Server to display the New Server dialog box (see Figure 8). You first select the Server Type and enter a Caption to display. The remainder of the dialog box changes depending on the server type you select.
Chapter 4: Accessing Data
81
Figure 8. Add a new OLAP server in the New Server dialog box. OLE DB (ADO) OLE DB is a fairly new technology developed by Microsoft as a replacement for ODBC. Where ODBC is designed to connect to relational data, OLE DB can connect to any type of data. OLE DB itself is a low level interface only used directly by C++ programmers. ADO is a COM wrapper around OLE DB that makes the data accessible to other development languages such as Visual FoxPro, Visual Basic, Delphi, and others. When you choose the OLE DB (ADO) source, Crystal Reports displays the OLE DB (ADO) dialog box (see Figure 9).
82
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 9. The first step in using an OLE DB or ADO connection is choosing the OLE DB provider or data link file. In this dialog box, select the OLE DB Provider or data link file to use for connecting to the data. It is possible the data link file contains all the necessary connection information. If it does, click Finish. Otherwise, click Next to go to the next step. The Connection Information panel displays (see Figure 10).
Chapter 4: Accessing Data
83
Figure 10. Enter server and connection information in the Connection Information dialog box. In this dialog box, you enter connection information such as server name, logon username, password, and set the database to use. If you want to use the default values for additional parameters, click Finish. Otherwise, click Next to display the Advanced Information dialog box (see Figure 11).
84
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 11. You change additional OLE DB parameters in the Advanced Information dialog box. To change a particular value, select it in the list, and then click Edit Value. When you have made all the necessary changes, click Finish. xBase Crystal Reports can natively connect to dBase II, dBase III and FoxPro 2.x tables. If you have data in Visual FoxPro tables, you need to either copy the data to a FoxPro 2.x table or connect to it using the Visual FoxPro OLE DB Provider. When you select xBase from the Available Data Sources list in the Database Expert, Crystal Reports displays a File Open dialog box to select the DBF file you want to include. You need to add the tables one at a time until all the necessary tables are added to the Database Expert. More Data Sources If the data source you want to use is not listed in the Database Expert, select More Data Sources. This list shows the data sources you did not select when you installed Crystal Reports.
Chapter 4: Accessing Data
85
Select the data source you want to use. Crystal Reports may launch the Install on Demand feature of Windows Installer to install the required database drivers. SQL Commands Crystal Reports 9.0 introduces the concept of SQL Commands. They are designed to replace the Crystal Query application. SQL Commands are a powerful feature that let you define a SQL Select statement to pull data from a single table or multiple tables. This makes it easy for developers to provide data to users who create their own report. The following steps show you how to add a SQL Command: 1.
Add the desired connection in the Database Expert
2.
Expand the tree for the connection (see Figure 12).
Figure 12. To add a SQL Command, expand your selected database in the Database Expert and select Add Command.
86
CrysDev: A Developer’s Guide to Integrating Crystal Reports 3.
Double-click Add Command to display the Modify Command dialog box (see Figure 13).
Figure 13. Enter the SQL Select statement in the Modify Command dialog box. 4. 5.
Enter the SQL Select statement to create the desired result set. If the statement is complete, proceed to step 12. Otherwise, continue with step 5. If you need to enter a parameter (Figure 13 shows the parameter pCountry), click Create to display the Command Parameter dialog box (see Figure 14).
6.
Enter the Parameter Name.
7.
Enter the Prompting Text.
8.
Select the Value Type.
9.
Enter the Default Value.
10. Click OK to save the parameter information and return to the Modify Command dialog box. 11. Repeat steps 6 through 10 to enter additional parameters as needed. 12. If desired, select Add to Repository. When you do this, the Add Item dialog box displays. (See “Understanding the Crystal Repository” later in this chapter.) 13. Click OK to close the Modify Command dialog box.
Chapter 4: Accessing Data
87
Figure 14. Specify the SQL Select parameters in the Command Parameter dialog box. There is one important note about command parameters. If the parameter is a character data type, you must surround it by single quotes in the SQL Select statement as shown in Figure 13. This is not required for other data types. Parameters fields, explained in detail in Chapter 6, “Advanced Reporting,” are similar to command parameters.
Selecting database objects Now that you selected the database connections for the report, you need to specify the tables to use. To see the available tables, expand the connection under the connection type or Current Connections in the Available Data Sources list in the Database Expert. Drill down under the appropriate node in the list. By default, Crystal Reports shows the tables, views, and stored procedures of the data source, if they are supported (see Figure 15). To add a table to the report, drill down to the desired table, view, or stored procedure and drag it from the Available Data Sources list to the Selected Tables list. You can also select tables from the Favorites and Repository the same way.
88
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 15. Drag the table from the Available Data Sources list to the Selected Tables list in the Database Expert. If you select a stored procedure, Crystal Reports will prompt you to enter a value for any required parameters (see Figure 16). You do not need to enter the parameters at this time. Crystal Reports will prompt the user to enter the values when the report is run.
Chapter 4: Accessing Data
89
Figure 16. Crystal Reports will prompt for required parameters if you select a stored procedure.
Linking Tables Once you add tables to the report, you need to tell Crystal Reports how to link them. This is done on the Links page of the Database Expert. Figure 17 shows four tables being linked. Some fields are indexed, as indicated by the pointers next to the field name. When you look at this in Crystal Reports, the pointers are different colors. Click Index Legend to see definitions of the different colors.
90
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 17. Crystal Reports makes its best guess at linking tables. When Crystal Reports links the tables, it makes its best guess at which fields to use for linking the tables. It does this by comparing field names in the tables. In Figure 17, Crystal Reports guessed Customers.PostalCode should link to Employees.PostalCode. However, the correct link should be Orders.EmployeeID to Employees.EmployeeID (see Figure 18). The following steps show how to make the correct link: 1.
Click the line with the incorrect link to select it. The link displays bold.
2.
Press the Delete key or right-click and select Delete Link from the shortcut menu.
3.
Drag the linking field from the parent table onto the linking field in the child table.
Chapter 4: Accessing Data
91
Figure 18. A view of the Database Expert Links page after correcting the linking information. Crystal Reports assumes the fields to use for linking should be the same value (equal to) and it should perform an inner join. To modify this, right-click the line indicating the link and select Link Options from the shortcut menu. The Link Options dialog box displays (see Figure 19). Make your changes, and then click OK to save them.
Figure 19. Use the Link Options dialog box to modify how tables are linked.
92
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Field definition files Normally, data fields in a report are bound to a field in a specific table. However, you can create unbound reports, and then apply the actual data source at runtime using a field definition file. The advantage of a field definition file is it is easy to change the actual data source at report time. Field definition files are tab separated text files with a TTX extension. Each line of the file represents one column in the data source. You must specify the field, data type (see Table 1), and length for string fields. Table 1. Data Types for Field Definition Files. Data Type Blob Boolean Byte Currency Date Long Memo Number Short String
Creating a field definition file You can create a field definition file using a text editor or you can use the designer in Crystal Reports. 1.
In the Database Expert, expand the Create New Connection node and select Field Definitions Only. The Field Definitions Only dialog box (see Figure 20) displays.
Chapter 4: Accessing Data
93
Figure 20. Use the Field Definitions Only dialog box to specify the TTX file for unbound reports. 2.
Enter either the name of an existing TTX file or click Create File. If you click Create File, the Database Definition Tool (see Figure 21) displays.
94
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 21. Use the Database Definition Tool to specify field information for a TTX file. 3.
Enter the Field Name for the first field in the table.
4.
Enter the Field Type for the second field in the table. If you select String, it will prompt you to enter the field Length.
5.
Optionally enter Sample Data.
6.
Click Add.
7.
Repeat steps three through six for each field in the table.
8.
When you finish, close the dialog box or select File | Save from the menu. It will prompt you to enter the file name if you created a new file, and then return to the Field Definitions Only dialog box.
9.
Click Finish to return to the Database Explorer.
Using a field definition file Once you create the field definition file, you add it to the report just like any other data source. However, you still need to link the report to the actual data. 1.
Open the report. If you preview the report at this time, it uses the sample data you placed in the TTX file.
Chapter 4: Accessing Data 2.
Select Database | Set Datasource Location from the menu. The Set DataSource Location dialog box (see Figure 22) displays.
Figure 22. You change the location of the database in the Set Datasource Location dialog box. 3.
In the top pane, select the specified table from the TTX file.
4.
In the bottom pane, select the actual data source.
5.
Click Update.
6.
Preview the report to verify it is using the actual data.
Working with Images I have seen many questions over the past few years asking how to handle images. Putting a single image on a report is easy, but when each detail record needs a different image, it’s difficult to make it work.
95
96
CrysDev: A Developer’s Guide to Integrating Crystal Reports
There are two methodologies to handling images. One is storing the image in a field in the database. The second, and probably more accepted method, is keeping an image file on disk and storing the filename in the database.
Images in the database Crystal Reports supports Windows Metafiles, Bitmaps (BMP), TIF, JPG, and PNG file formats. It does not support GIF files. I tested images stored in four different data sources: FoxPro, Visual FoxPro, Access, and SQL Server. In a FoxPro or Visual FoxPro table, images are stored in a General field. When using native data connections to a FoxPro table, Crystal Reports does not recognize the general field. The image does not print in the report. However, if you use ODBC or the Visual FoxPro OLE DB Provider, the General field is recognized and the image prints in the report. Access stores images in an OLE Object field. The images print correctly using direct access, ODBC, and ADO. In SQL Server, you store the pictures in an Image file. Using both ODBC and ADO, the images print correctly. separate image files for each record requires you hook into the formatting Using events of Crystal Reports. Chapter 15, “Integrating COM Components,” discusses Event handling in detail.
Adding a watermark Watermarks are images or text that prints behind the report data. Use the following steps as a guide to add a watermark under the detail section of a report. 1.
Right-click the Page Header, to the left of the design area, and select Insert Section Below from the shortcut menu.
2.
Place the graphic or text in the new section.
3.
Select Report | Section Expert from the menu or click the Section Expert button on the Expert Tools toolbar to display the Section Expert (see Figure 23).
Chapter 4: Accessing Data
Figure 23. Use the Section Expert to set options for each report section. 4.
Select the newly added section in the Sections list box.
5.
Select the Underlay Following Sections check box.
6.
Click OK to return to the designer.
7.
Preview the report.
8.
Return to the design tab and stretch the graphic vertically until it is tall enough to underlay they entire Details section.
Limiting records selected When you apply a record selection criteria, Crystal Reports adds a Where clause to the SQL Select statement sent to the database. You can use the Select Expert or Selection Formulas in the Formula Workshop (see Chapter 8, “Using Formulas”). Either way gives the same results.
97
98
CrysDev: A Developer’s Guide to Integrating Crystal Reports
The Select Expert Basically the Select Expert is a wizard that makes it easy to apply a criteria select statement. The following steps walk you through using the Select Expert. 1.
Choose Report | Select Expert from the menu or click the Select Expert button on the Expert Tools toolbar.
2.
If you don’t have any criteria entered, such as the first time you display the Select Expert, the Choose Field dialog box (see Figure 24) displays.
Figure 24. Use the Choose Field dialog box to pick the first field for the Select Expert. 3.
Select the field for the criteria and click OK to return to the Select Expert (see Figure 25).
Chapter 4: Accessing Data
Figure 25. Use the Select Expert to limit the data used in the report. 4.
In the first combo box, choose the comparison for the field.
5.
In the second combo box, choose the value.
6.
Click Show Formula to display the formula Crystal Reports will apply (see Figure 26). You can also enter the same formula in the Formula Workshop.
Figure 26. The Select Expert expanded to show the selection formula.
99
100
CrysDev: A Developer’s Guide to Integrating Crystal Reports 7.
To add additional criteria, click New or click OK to save the criteria and close the Select Expert.
8.
Preview the report to see the filtered data.
Miscellaneous data functions Crystal Reports has a few other data related functions you should know about.
Set Database Location It’s common to use a different data set during development than at runtime. This makes it necessary to change the location of the data and maybe even the type of data access. For example, you may develop a report using direct access FoxPro data, but at runtime you need to access data on SQL Server. To change the location of the data: 1.
Select Database | Set Database Location from the menu. The Set Datasource Location dialog box (see Figure 22) displays.
2.
Choose the table in the Current Data Source list.
3.
Select the new data source or create a new connection in the Replace with list.
4.
Click Update to change the location and convert the database driver Crystal Reports uses.
5.
Click Close to close the Set Datasource Location dialog box.
6.
Select Database | Verify Database from the menu to confirm the new database is the same structure as the old database.
LogOn or Off Server This option does exactly what it says. It logs you on or off a server. If you have a report open, select Database | LogOn or Off Server from the menu. If you do not have a report open, select File | LogOn or Off Server. With either option, the Data Explorer (see Figure 27) displays.
Chapter 4: Accessing Data
101
Figure 27. Use the Data Explorer to log on or off a database server. To log on the server, select the server from the list or create a new connection and click Log On. To log off, select the server and click Log Off.
Show SQL Query This option displays the Show SQL Query dialog box (see Figure 28) showing the SQL Select statement sent to the database. To display the dialog box, select Database | Show SQL Query from the menu.
102
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 28. The Show SQL Query dialog box displays the SQL Select statement sent to the database.
Perform Grouping on Server When selected, this option can provide significant performance increases, particularly when used with client/server databases such as SQL Server and Oracle. If selected, a Group By clause is added to the SQL Select statement sent to the database. To toggle this option, select Database | Perform Grouping on Server from the menu or set this option in either the Options or Report Options dialog box.
Report Bursting Indexes Sometimes you may want to save the data with the report. When you do this, you can improve the reporting performance by adding indexes to the data. Select Report | Report Bursting Indexes from the menu to display the Saved Data Indexes dialog box (see Figure 29).
Chapter 4: Accessing Data
103
Figure 29. Select fields for indexing in the Saved Data Indexes dialog box to increase reporting speed in reports using saved data. Select the fields you want indexed in the Available Fields list. When you finish, click OK.
Summary In this chapter, I showed you how to connect to many commonly used data sources. Crystal Reports can connect to many others, such as NT Event Logs, IIS Logs, Outlook, Lotus Domino servers, and many others. While I didn’t explain many of these data sources, you should have no trouble connecting to them. Updates and corrections to this chapter can be found on Hentzenwerke’s web site, www.hentzenwerke.com. Click “Catalog” and navigate to the page for this book.
104
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Chapter 5: Intermediate Reporting
105
Chapter 5 Intermediate Reporting This chapter shows you how to do some very common reporting needs. These including grouping, totaling, drill-down, graphs, and cross tabs. Also, Crystal Reports 9 adds a new feature called the Repository. You will see how Crystal Reports makes easy work out of something that seems complicated.
In previous chapters, you have seen how to install Crystal Reports, create a report, connect to data, and learned about some important default settings. However, the capabilities you have used up to this point will rarely suffice. You almost always need to be able to do grouping and totaling. Many users also want graphs or maps as part of their report in order to better analyze their data. Sometimes a report requires essentially a view of the data turned 90 degrees, where the columns are turned into rows and rows into columns. Crystal Reports can handle all of these needs and more.
Understanding the Crystal Repository The Crystal Repository is a new feature introduced in Crystal Reports 9. It is used to store text objects, custom functions, images, and SQL Commands commonly used in reports. Putting an object from the repository onto a report is an easy drag-and-drop procedure. When you install Crystal Reports, it installs the repository database. By default it uses an Access database, Repository.MDB. On my system, it was placed in C:\Program Files\Common Files\Crystal Decisions\2.0\bin. A System DSN ODBC connection named Crystal Repository is also set up during installation. Because the repository database is accessed via an ODBC connection, you can use any back end you like. Create the database and tables, create the ODBC connection, and then edit ORMap.INI to point to the new Repository database. Display the Repository Explorer by selecting View | Repository Explorer from the menu or clicking the Repository Explorer button on the Standard toolbar. Figure 1 shows the default items in the Repository Explorer.
Figure 1. Use the Repository Explorer to navigate objects stored in the Crystal Repository.
106
CrysDev: A Developer’s Guide to Integrating Crystal Reports
One use of the repository is the ability to modify objects used across multiple reports. Modify the object in the repository and then open each report to update the object stored in the report. Another use of the repository is sharing objects across users. For example, you can create complex queries and make them accessible to end users creating their own reports.
Adding objects to the repository The steps required to add an object to the repository vary depending on the object. I discuss text objects, images, and SQL Commands here. Custom Functions are discussed in Chapter 8, “Using Formulas.” Text objects and images Text objects and images are added to the repository directly from the report. 1.
Right-click the object on the report or in the Report Explorer.
2.
Select Add to Repository from the shortcut menu. The Add Item dialog box displays (see Figure 2).
Figure 2. Use the Add Item dialog box to specify the name and location of each object you add to the repository.
Chapter 5: Intermediate Reporting 3.
Enter the Name of the object. This is the name the Repository Explorer displays.
4.
Enter the Author.
5.
Enter a Description of the object.
6.
Select the repository folder to hold the object.
7.
Click OK to add the object and return to the report.
107
SQL Commands In Chapter 4 “Accessing Data,” I introduced the concept of SQL Commands. One of the options in the Modify Command dialog box is Add to Repository. When you select this option, Crystal Reports displays the Add Item dialog box when you save the SQL command.
Using repository objects in a report Once you have objects in the repository, you can add them to a report. How you do this depends on the type of object. SQL commands are added through the Database Expert. Custom Functions are added from the Formula Workshop. To add a text or image object, simply drag-and-drop it from the repository onto the report. The object is locked, meaning it is placed on the report in a read-only state. In the case of a text object, you cannot alter the appearance of the text because it uses the properties from the repository. If you need to modify the object on the report, right-click on the object and select Disconnect from Repository from the shortcut menu.
Updating objects in the repository Sometimes it becomes necessary to modify objects stored in the repository. You modify Custom functions in the Formula Workshop and SQL commands in the Database Expert. The following steps explain how to modify a text object: 1.
Right-click the text object in Design view.
2.
Select Disconnect from Repository from the shortcut menu.
3.
Make the desired modifications.
4.
Right-click the object and select Add to Repository. The Add Item dialog box displays (see Figure 2).
5.
Enter the name of the object and select the repository folder.
6.
Click OK to save the object. If you use the same repository name, it will prompt you to update the original object with the changes.
When you update a repository object, it affects all the reports that use the object. However, you must modify those reports before the changes take affect. The objects automatically update when you open the report.
108
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Sorting Sorting puts the data in a specific order. For example, a customer list is often ordered alphabetically. To sort the data, select Report | Record Sort Expert from the Crystal Reports menu or click the Record Sort Expert button on the Expert Tools toolbar and the Record Sort Order dialog box (see Figure 3) opens.
Figure 3. Use the Record Sort Order dialog box to sort data in the report. The left side of this dialog box displays a list of available fields. On the right are the selected fields. Each field you select can be sorted in Ascending or Descending order. The A or D in front of the item indicates the sort direction for the field. When you have selected the fields and sort order, click OK to save your selections. Note that you cannot change the sort direction for group fields. Record sorting does not add any sections to the report, but simply orders the data.
Groups Groups are similar to sorting, in that the data is ordered a specific way. However, grouping adds a group header and footer section to the report and is often used to provide totals for each group. It is not necessary to sort the data before grouping, as grouping sorts by default. You add a group by selecting Insert | Group from the Crystal Reports menu to display the Insert Group dialog box (see Figure 4).
Chapter 5: Intermediate Reporting
109
Figure 4. Use the Common tab of the Insert Group dialog box for creating a group. The Common tab allows you to select the field to group by and its sort order. You can choose from four sort orders: •
Ascending order
•
Descending order
•
Specified order
•
Original order
Ascending and descending orders are self-explanatory. Original order prints the data in the same order it appears in the data. Specified order requires some explanation. Specified order lets you determine how you want the data to display. When you select this option, two new tabs, Specified Order (see Figure 5) and Others, are added to the dialog box (see Figure 6).
110
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 5. Use the Specified Order tab of the Insert Group dialog box to determine which data you want to see on the report. Here’s how this page works. The Named Group: box contains the group data from the table. Select the data you want to see and that item is added to the list. You can change the order of the displayed data. Only the groups you select appear in the report. Once you select one item from the Named Group: box, a fourth tab, Others, is added to the dialog box. The Others tab (shown in Figure 6) lets you determine how to handle the rest of the data. The default is to group them all together in a group called Others. You can also discard them or leave them in their own group.
Chapter 5: Intermediate Reporting
111
Figure 6.The Others tab is where you determine how to handle the unspecified data. The Options tab (see Figure 7) of the Insert Group dialog box is used to select any group options that you want. By default, Crystal Reports uses the field selected for grouping as the name of the group. You can change this by selecting Use a Formula as Group Name and choosing a different field or formula for the group name. Formulas are discussed in Chapter 8, “Using Formulas.”
Figure 7. Use the Options tab to set options for the group.
112
CrysDev: A Developer’s Guide to Integrating Crystal Reports
You can also select Keep Group Together to force the entire group to print on a single page if it is short enough. Finally, if you check Repeat Group Header On Each Page, the group header section prints at the top of each page the group prints on. Once you finish setting the group options, the new sections are added to the report. This is not the end of what you can do with a section. If you right-click the section description, you see a shortcut menu (see Figure 8) with additional options.
Figure 8. The Group shortcut menu displays by right-clicking the group description. At the top of the shortcut menu is the grouping. It is either Group Header or Group Footer and the field you chose to group on. The letter ‘A’ means this is section A of the group header. Select Insert Section Below to add additional sections to the group header or footer. Hide (Drill-Down OK) hides the section from the report, but displays the drill-down list. Drill-down is explained later in this chapter. Once you select this option, the menu prompt changes to Show. Suppress (No Drill-Down) hides the section and does not allow drill-down. When you select this option, the menu item changes to Don’t Suppress. Section Expert displays the Section Expert, discussed in Chapter 2, “Touring Crystal Reports.” Change Group displays the Change Group Options dialog box, which is the same as the Insert Group dialog box (see Figure 4), but with a different caption.
Chapter 5: Intermediate Reporting
113
Show Short Section Names expands and collapses the left area of the designer. So, instead of showing “Group Header #1”, the short section name, “GH1”, displays. This increases the size of the design area. The Insert Line, Delete Last Line, and Arrange Lines work with Guidelines, discussed in Chapter 2, “Touring Crystal Reports.” Fit Section vertically sizes the section to be the same vertical height as the data it contains. Insert Section Below adds a new section below the current one. The new section is part of the same area. Delete Group removes the entire group from the report. If you choose to delete the group, Crystal Reports displays a warning that the operation cannot be undone. Select All Section Objects selects each report object in the section.
Drill-down By default, when you add a new group, it is available for drill-down. Drill-down allows you to double-click a group and zoom into its data. There are two ways to do this. The first is using the Group Tree on the left side of the preview window. When you double-click a group item, the data in the current preview window repositions to show the selected group. The second method allows you to double-click the group in the preview window. A new preview opens containing only the data for the selected group. There are a couple different ways you can suppress group data and drill-down through the group shortcut menu (see Figure 8). First, you Hide the group. When you select this option, the group does not print on the report and the data does not display in the preview window. However, the group data does show in the Group Tree. The second method, Suppress, completely hides the group.
Hierarchical groups Sometimes you need to relate data in a table to another field in the same table. For example, an Employee table may have a field that points to the employee number for the supervisor (a self join). In this case, the supervisor record is the parent and the employee record is the child. Crystal Reports makes it easy to create a report listing the supervisor followed by the employees that report to him. The following steps show you how to create a hierarchical grouping. 1.
Add a group to the report for the child record.
2.
Place any additional data you need into the group header.
3.
Select Report | Hierarchical Grouping Options from the menu. The Hierarchical Options dialog box displays (see Figure 9).
114
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 9. Use the Hierarchical Options dialog box to add hierarchical grouping to the report. 4.
Select the group from the Available Groups list.
5.
Select the Sort Data Hierarchically check box.
6.
Select the Parent ID Field.
7.
Enter the number of inches to indent the child records.
8.
Click OK to save the grouping.
When you preview or print the report, Crystal Reports correctly matches up the data based on the hierarchy link you select.
Summaries Summaries are used to add or summarize a column of data or specified fields in a column in the report. Totaling on a line requires using a formula, which I discuss in Chapter 8, “Using Formulas.” Another type is called running totals, presented later in this chapter.
Subtotals and grand totals Subtotals add the values of a specified column and place the result in a group footer. Grand totals are printed at the end of the report. To add a summary to your report, select Insert | Summary from the Crystal Reports menu or click the Insert Summary button on the Insert Tools menu. The Insert Summary dialog box appears (see Figure 10).
Chapter 5: Intermediate Reporting
115
Figure 10. Use the Insert Summary dialog box to add a subtotal or grand total to a report. The Choose the field name to summarize box is where you select which field you want to summarize. If you select the field in the report before displaying the Insert Summary dialog box, that field displays in the combo box. The Calculate this summary box is where you select the type of summary to make. The items in the list change depending on the data type of the field you select to summarize. For example, you can calculate the average, sum, or variance of numeric data, but can’t for character data. Next, select the summary location. The choices are the footer sections of each group or a grand total at the end of the report. Click Insert Group to display the Insert Group dialog box and add a new group to the report. Depending on the data type of the summarized field and the type of summary you select, the additional options are enabled or disabled. You can show the summary as a percentage of another field or summarize across hierarchies.
116
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Running totals Running totals are different from group and grand totals. A running total is generally placed on a detail line and incremented by the specified value throughout the report. The following steps show you how to add a running total. 1.
Select Running Total Fields in the Field Explorer.
2.
Click New on the Field Explorer to display The Create Running Total Field dialog box (see Figure 11).
Figure 11. Use the Create Running Total Field dialog box to add a running total to a report. 3.
Enter a name for your running total.
4.
Select the field to total.
5.
Select the summary type.
6.
Determine when to evaluate the field. You can have the field calculate for each record, when a specified field changes, when a group changes, or based on a formula.
7.
Determine when to reset the value. You have the same options as Evaluate.
Chapter 5: Intermediate Reporting
117
8.
When you finish setting the options for the running total, click OK. It returns to the Field Explorer.
9.
Drag-and-drop the running total field from the Field Explorer onto the designer.
Crystal Reports automatically calculates the running total when you print or preview the report.
Cross-tabs Cross-tabs are a powerful data analysis tool that allows you to easily summarize data based on two or more fields. Think of it as a spreadsheet, where you have columns and rows of data and the intersection is the summarized data. To add a cross-tab, select Insert | Cross-Tab from the menu or click the Insert Cross-Tab button on the Insert Tools toolbar. The Cross-Tab Expert displays (see Figure 12).
Figure 12. You define a cross-tab using the Cross-Tab Expert. To create the cross-tab, drag the fields from the Available Fields list and place them where you want the field to appear in the report. By default, summarized fields are calculated as the sum of the selected field. In Figure 12, the data is totaled by Orders.Order Date. The column heading is Employee.Last Name. Each intersection of a row and column consists
118
CrysDev: A Developer’s Guide to Integrating Crystal Reports
of two numbers, the sum of the Order Amount and the count of the orders made for each date and employee. On the left side of the Cross-Tab is the list of available fields and formulas. You pick a field or add a formula with the New Formula button. If you edit or create a formula, the Formula Workshop displays. Formulas are explained in Chapter 8, “Using Formulas.” Both the Columns and Rows lists have Group Options buttons. Select a field in the list to enable the button. When you click Group Options, the Cross-Tab Group Options dialog box displays (see Figure 13). The actual options that appear depend on the date type of the selected field.
Figure 13. Use the Cross-Tab Group Options dialog box to set options for the row or column field. When you select a field in the Summarized Fields list, the Change Summary button enables. Click this button to display the Edit Summary dialog box (see Figure 14).
Chapter 5: Intermediate Reporting
119
Figure 14. The Edit Summary dialog box lets you change the summary type for the summarized field. When you finish selecting all the fields and summaries for the cross-tab, select the Style tab of the Cross-Tab Expert (see Figure 15). On this tab you select the formatting to apply to the cross-tab or select Custom from the style list to apply your own formatting once the crosstab is placed on the report.
120
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 15. The Style tab of the Cross-Tab Expert is where you format the look of the cross-tab. The last step is to apply any custom formatting to the cross-tab. You can do this even if you select an existing style. You add the custom formatting on the Customize Style tab of the Cross-Tab Expert (see Figure 16).
Chapter 5: Intermediate Reporting
121
Figure 16. You further customize the formatting of the cross-tab on the Customize Style tab. There are many different settings you can set for each row, column, label, or even the grid lines. Click Format Grid Lines to display the Format Grid Lines dialog box (see Figure 17).
122
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 17. Further customization of the cross-tab can be done in the Format Grid Lines dialog box. When you finish selecting all the fields and formatting for the cross-tab, click OK to close the Cross-Tab Expert. You then place the cross-tab on the report section where you want it to appear. Figure 18 shows a preview of the cross-tab.
Chapter 5: Intermediate Reporting
123
Figure 18. The formatted results of the cross tab.
Charts Presenting data in a graphic format is very important to some users. Crystal Reports uses the term “charts” instead of graphs. I use the two terms interchangeably. Crystal Reports gives you fourteen different graph types to choose from and some can be presented horizontally or vertically, some two-dimensional or three-dimensional. Here’s a list of the available chart types. •
Bar
•
Line
•
Area
•
Pie
•
Doughnut
•
3D Riser
•
3D Surface
•
XY Scatter
•
Radar
•
Bubble
•
Stock
124
CrysDev: A Developer’s Guide to Integrating Crystal Reports •
Numeric Axis
•
Gauge
•
Gantt
Basic charting Creating a chart is fairly simple. Note that some of the options change depending on the chart type you select. To create a chart, select Insert | Chart from the menu or click the Insert Chart button on the Insert Tools toolbar. The Chart Expert displays (see Figure 19).
Figure 19. Use the Type tab of the Chart Expert to select the chart type. The Type tab The Type tab of the Chart Expert is where you select the type of chart you want. If your selected chart supports vertical or horizontal alignment, those options are available. If Automatically set chart options is not selected, the Axes and Options tabs are added to the dialog box, depending on the chart type. For example, the Axes tab isn’t available with a pie chart.
Chapter 5: Intermediate Reporting
125
The Data tab On the Data tab (see Figure 20) you set several chart features. First is where to place the chart. You can place it in the header or footer of each group or the report itself. Next, there are four options based on your selection in the Layout grouping. In the Advanced option you set which fields to chart. Options are available for TopN records and you can order the data how you want. You can also change the summary option (for example, average instead of sum) or choose not to summarize the values.
Figure 20. The Layout option on the Data tab determines how you want the chart to appear and what fields to use. The Group button only enables if you have a group subtotal or summary value and is used to set the grouping options for the graph. If you are charting a cross-tab, the Cross-Tab option enables. This option allows you to choose which items in the cross-tab to graph. The Axes tab The Axes tab (see Figure 21) is only available if you clear the Automatically set chart options check box on the Type tab of the Chart Expert. You use the Axes tab to customize the axes and grid lines of the chart. Options let you turn on or off grid lines, set the data values and range, and the number of divisions on the chart.
126
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 21. Use the Axes tab of the Chart Expert to set options for the chart axes. The Options tab The Options tab (see Figure 22) is where you change miscellaneous chart settings. On this tab, you can determine if the chart will be color or black and white. When you set the chart to print black and white, each section prints with a different line or cross hatch pattern.
Chapter 5: Intermediate Reporting
127
Figure 22. On the Options tab of the Chart Expert, you can change several display options for a graph. Crystal Reports gives you the ability to assign a specific color to any data item. Click Format to display the Chart Color Format Expert (see Figure 23).
Figure 23. Customize the colors of individual chart items in the Chart Color Format Expert.
128
CrysDev: A Developer’s Guide to Integrating Crystal Reports
You can also set the data points. The options, depending on chart type, are None, Show label, or Show value. Options are also provided to change the marker shape and size. Finally, you can change the location of the Legend. The Text tab The last tab is the Text tab (see Figure 24). On this tab, you change the text and fonts for the different captions and labels on the chart.
Figure 24. Use the Text tab of the Chart Expert to set the captions and fonts for the graph. Once you have set the chart options, you drop the chart into a report section just like any other field. The Design tab of the Crystal Reports designer shows a representation of the chart. However, when you preview the report, you see the actual chart. While in the preview, you can double-click a section of the chart to drill-down into the detail data behind it.
Advanced charting After you place the chart on the report, you can set additional chart options. Right-click the chart and select Format chart from the shortcut menu. Several options are available, depending on the chart type and formatting selected. Advanced charting is beyond this book. I encourage you to explore these features on your own.
Chapter 5: Intermediate Reporting
129
Maps Maps are closely related to charts, in that they graphically represent data. However, in this case, the graphics represent a geographic breakdown. To add a map to a report, select Insert | Map from the menu or click the Insert Map button on the Insert Tools toolbar. The Map Expert dialog box displays.
The Data tab The first step (see Figure 25) of inserting a map is to choose its placement on the report. The map can be placed at any group break, at the beginning, or at the end of a report. After setting the map placement, you determine how to arrange the data. First, select the Geographic field. This can be a state or country. Next, add the Map values. These are the data points you want to map out. For example, total sales by country.
Figure 25. Use the Data tab of the Map Expert to determine which fields to map.
130
CrysDev: A Developer’s Guide to Integrating Crystal Reports
The Type tab Once you determine the data to map, you pick the map type (see Figure 26). The options available to you depend on the map type you select.
Figure 26. The Type tab of the Map Expert is where you select the type of mapping to chart and the options for each map type.
Chapter 5: Intermediate Reporting
The Text tab The final step of the Map Expert is to set the text you want to display (see Figure 27).
Figure 27. Set the caption and legend options for the map on the Text tab of the Map Expert. Once you have set the map options, the map displays on the report. In design mode, you only see a representation of the map. However, the map displays in the preview (see Figure 28).
131
132
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 28. A preview of the map.
Summary Crystal Reports gives you the ability to reuse report objects through the use of the Repository. Grouping and sorting is quick and easy through the various Expert windows. Summary data can be made on any field and with many different summary options. Finally, Crystal Reports provides powerful, yet easy to use, charting and mapping capabilities. Updates and corrections to this chapter can be found on Hentzenwerke’s web site, www.hentzenwerke.com. Click on “Catalog” and navigate to the page for this book.
Chapter 6: Advanced Reporting
133
Chapter 6 Advanced Reporting Crystal Reports offers a number of advanced features reports such as parameters, alerts, embedded files, and hierarchical reporting. You won’t use these features all the time, but they offer a lot of power and ease-of-use when you need them.
Now that you have seen how to create reports and learned about powerful capabilities such as mapping and charting, it’s time to look at other features you may not need often, but provide a lot of flexibility to your reports.
Report parameters Many times you will need to pass data not in a database to a report. For example, you may need SQL SELECT criteria, sort order, filters, report titles, etc. This data can be passed via report parameters. You use the parameter just like a regular field or as part of a formula. (Formulas are explained in detail in Chapter 8, “Using Formulas.”) The following steps walk you through creating a parameter: 1.
In the Field Explorer, click Parameter Fields and then click New. The Create Parameter Field dialog box (see Figure 1) displays.
Figure 1. Use the Create Parameter Field dialog box to enter a new parameter.
134
CrysDev: A Developer’s Guide to Integrating Crystal Reports 2.
Enter the Name for the parameter field.
3.
Enter the Prompting text. This displays to the user when the report is run.
4.
Select the Value type. You can choose Boolean, Currency, Date, DateTime, Number, String, or Time.
5.
If the parameter accepts multiple values, set those options. See “Multiple value parameters” later in this chapter.
6.
If you want default values, click Set default values. See “Default values” later in this section.
7.
Click OK to save the parameter settings.
The new parameter appears under Parameter Fields in the Field Explorer. Drag the field from the Field Explorer onto the report. When the report is run, the Enter Parameter Values dialog box displays (see Figure 2).
Figure 2. The Enter Parameter Values dialog box displays when you run the report.
Chapter 6: Advanced Reporting
135
Multiple value parameters Sometimes you may want to enter multiple values for a single parameter. For example, you may want to report sales figures for specific states. To allow multiple values, select Allow multiple values” in the Create Parameter Field dialog box. You then have three options to choose for the parameter: discrete values, range values, or both discrete and range values. The multiple parameters are passed to the report as an array. You use each parameter by referencing the appropriate array element. For example, if you have a parameter called MultipleStates, you reference the second value with: {?MultipleStates}[2]
Chapter 8, “Using Formulas,” discusses formulas and arrays in detail. Discrete values Select discrete values if you need to enter specific values. For example, you may want to report on sales in California, Utah, and Nevada. When you run the report, it prompts you to enter each value (see Figure 3).
Figure 3. You can enter multiple discrete parameter values when you run the report.
136
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Range values Range values are typically used for numeric or date data. For example, you may want to report on sales for a specific date range and only between two amounts. When you run the report, you enter the range of values (see Figure 4).
Figure 4. You enter a range of values in the Enter Parameter Values dialog box. Discrete and range values Finally, you can enter both discrete values and a range of values (see Figure 5).
Chapter 6: Advanced Reporting
137
Figure 5. Enter both a range of values and discrete values when you run the report.
Default values It is often a good idea to supply default values for each parameter. This prompts the user for the best selection or provides a value if the user doesn’t supply one. To enter default values, click Select default values in the Create Parameter Field dialog box (see Figure 1). The Set Default Values dialog box displays (see Figure 6).
138
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 6. You enter default values in the Set Default Values dialog box. Enter values from a table or key them in yourself. In Figure 6, the values California, Nevada, and Utah are from the States table. The value Oregon was entered in the textbox. Using either method, you need to click the mover button to add the item to the default values list. To add a description for each value, highlight the value in the list, and then click Define description to display the Define Description dialog box (See Figure 7).
Figure 7. Enter a description for each parameter value in the Define Description dialog box.
Chapter 6: Advanced Reporting
139
You can also import values from a text file. The file format is one value per line. If you provide a description, it is the second item on the line, separated from the value by a tab. When you import a pick list, the contents is added to the Default Values list. Once you enter the default values, you can set a number of options. The first determines the minimum and maximum length of the value. Next is an Edit mask. If you use an edit mask, the minimum and maximum length prompts are disabled. Table 1 lists the edit mask characters. Entry required means you must enter a value for the parameter when prompted. Table 1. Valid edit mask characters. Character(s)
Entry required?
Description
A a 0 9 # L ? & C .,:;-/
Yes No Yes No No Yes No Yes No No
< > \
No No No
Password
No
Any alphanumeric character Any alphanumeric character Any digit Any digit or space Any digit or space or the plus or minus sign Any letter Any letter Any character or space Any character or space Literals. Character inserted into the parameter at the location specified. Following characters converted to lowercase Following characters converted to uppercase Literal. Following character inserted into the parameter at the location specified. Makes the parameter password masked.
Next you determine what to display in the pick list. The options are Value and description or Description. Finally, you set the sort order and whether it is determined by the value or the description. After you set all the parameter options, click OK to return to the Create Parameter Field dialog box. In Chapter 10, “The RDC: Manipulating Data,” I show you how to use report parameters at runtime.
Report alerts Report alerts notify the user when a specified condition exists. For example, you may have a sale over specific amount and want to notify the user. Chapter 10, “The RDC: Manipulating Data,” shows how to use alerts at runtime. The following steps show you how to set up an alert and use it in the designer. 1.
Once you design your report, select Report | Alerts | Create or Modify Alerts from the menu. The Create Alerts Dialog displays (see Figure 8).
140
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 8. The Create Alerts window is where you add a new alert or select an existing alert to modify. 2.
Click New to display the Create Alert dialog box (see Figure 9).
Figure 9. Use the Create Alert dialog box to name an alert and enter the alert message. 3.
Enter the Name of the alert.
4.
Enter the alert Message. This message displays to the user when the alert is triggered.
Chapter 6: Advanced Reporting 5.
141
Click Condition to open the Formula Workshop (see Figure 10). Formulas are discussed in detail in Chapter 8, “Using Formulas.”
Figure 10. Enter the alert condition in the Formula Workshop. 6.
Click Save and Close to return to the Create Alert dialog box.
7.
Click OK to save the alert and return to the Create Alerts dialog box.
8.
Click Close.
When you run the report, if the condition exists, the alert displays (see Figure 11). Click View Records to add a tab to the designer containing the records that meet the alert criteria.
142
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 11. When the alert condition is met while running the report, the Report Alerts dialog box displays.
OLE objects You have already seen OLE objects in the form of images. However, it is possible to use files from other applications. For example, you can embed a Word document or an Excel spreadsheet in a report. The following steps guide you through adding a document. 1.
Select Insert | OLE Object from the Crystal Reports menu. The Insert Object dialog box appears (see Figure 12).
2.
To add a new object, select the Object Type. When you click OK, the application assigned to the object type launches.
3.
To add an existing object, click Create from File. The Insert Object dialog box changes allowing you to enter the file name (see Figure 13).
4.
You have the option of linking or embedding the object. To link the object, select Link. When an object is linked, any changes to the original document reflect in the report. If you embed the object (clear the Link option), the contents of the original object always prints on the report.
5.
To display only an icon of the object, select Display as Icon.
6.
Click OK to close the Insert Object dialog box.
7.
Drop the object on the report. Figure 14 shows an Excel spreadsheet embedded on a report.
Chapter 6: Advanced Reporting
Figure 12. Add a new OLE Object from the Insert Object dialog box.
Figure 13. Add an existing object from the Insert Object dialog box.
143
144
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 14. When you add an OLE object to a report, its contents display in the Designer. If you double-click the object in the designer, Crystal Reports uses in-place editing to modify the report. For example, if you double-click the Excel spreadsheet in Figure 14, the menus and toolbars would change to those of Excel. When you double-click the object in Preview, the appropriate application launches with the data. Again, using Figure 14, Microsoft Excel launches with the spreadsheet from the report.
Embedded fields In Chapter 2, “Touring Crystal Reports,” I briefly mention the ability to embed RTF and HTML text in a field in the database. I call these embedded fields. The ability to have preformatted text adds a lot of power to Crystal Reports. Once you drop text or a memo field on a report, set the Text Interpretation on the Paragraph tab of the Format Editor (see Figure 15).
Chapter 6: Advanced Reporting
Figure 15. Set Text Interpretation to use embedded HTML or RTF. Crystal Reports only supports the following HTML tags and attributes: html body div tr span font p br
h1 h2 h3 h4 h5 h6 center big
small b i s strike u align face
size color style font-family font-size font-style font-weight
145
146
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Hierarchical reports Sometimes you need to show related data from the same table. For example, you may want a report that lists each supervisor and their employees. This is called a hierarchical report. Crystal Reports treats this as a special type of grouping. The following steps demonstrate how to create a hierarchical report. 1.
Create a new blank report.
2.
In the Database Expert, select the Extreme database that ships with Crystal Reports. This is a Microsoft Access database.
3.
Select the Employee table from the database.
4.
Close the Database Expert.
5.
Create a new group with EmployeeID.
6.
Drag the Employee ID, Last Name, and First Name fields to the Group Header section.
7.
From the menu, select Report | Hierarchical Grouping Options. The Hierarchical Options dialog box displays (see Figure 16).
Figure 16. Use the Hierarchical Options dialog box to create hierarchical groupings. 8.
Select Sort Data Hierarchically.
9.
Select Employee.Supervisor ID as the Parent ID Field.
10. Enter 0.5 for the number of inches for the Group Indent. 11. Click OK to save the hierarchical options.
Chapter 6: Advanced Reporting
147
12. Preview the report (see Figure 17). You should see each supervisor listed with their employees indented underneath.
Figure 17. A preview of the hierarchical grouping report.
Summary Crystal Reports provides a number of advanced features you won’t use all the time, but they are great time savers that offer a lot of power when you need them. From what I have shown in the chapter, you will most likely use report parameters the most because they are useful in record selection criteria, filtering, sorting, grouping, and many other places. Updates and corrections to this chapter can be found on Hentzenwerke’s web site, www.hentzenwerke.com. Click “Catalog” and navigate to the page for this book.
148
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Chapter 7: Subreports
149
Chapter 7 Subreports Some reporting needs are very complex. In fact, they can be so complex a single report doesn’t provide all the information. You can solve this with multiple reports or you can use subreports to make the report seem like one report.
Subreports are one of the most powerful features in Crystal Reports. Basically, a subreport is a report embedded in another report. A subreport is just like a regular report except it is inserted in another report. You use a subreport to: •
Combine unrelated data into a single report.
•
Print the same data in different ways.
•
Combine data not easily related in other ways.
•
Do a one-to-many lookup from non-indexed data.
Crystal Reports supports two types of subreports, linked or unlinked. A linked subreport connects to the data in the parent report. The parent report drives the data in the linked report. In an unlinked report, the data is not connected in any way to the main report. Subreports can also be set to always print or you can have them only print on demand.
Inserting a subreport Subreports are created in two ways. You can use an existing report or create one to embed in the main report. The following steps explain how to add subreport. 1.
Select Insert | Subreport from the Crystal Reports menu or click Insert Subreport on the Insert Tools toolbar. The Insert Subreport dialog box (see Figure 1) displays.
2.
To use an existing file, select Choose a report and enter the file name or click Browse to select the report file.
3.
To create a new subreport, select Create a subreport and enter the subreport name. Click Report Wizard to begin designing the new subreport.
4.
To create an on-demand subreport, select the On-demand subreport check box. Ondemand subreports are discussed later in this chapter.
5.
When you finish selecting all the proper settings, click OK to save them. The Link page is explained in the “Linked subreports” section later in this chapter.
6.
Drop the subreport into any section on a report. The designer adds a new view for the subreport. The subreport displays as a rectangle in the report designer.
150
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 1. You specify the subreport in the Insert Subreport dialog box. When you create a new subreport, a new RPT file is not created. Instead, the subreport exists only in the main report. If you close the tab for the subreport, double-click it in the designer to edit it. If you choose an existing report file, the subreport is embedded in the main report. The reports are not linked, meaning if you make changes to the subreport, they will not be reflected in the original RPT file and vice-versa. I recommend making any changes to the original RPT file and then right-click the subreport in the main report and select Re-import subreport from the shortcut menu to bring the changes into the subreport.
Unlinked subreports The easiest way to add a subreport is to add an unlinked one. An unlinked subreport is independent from the main report. An unlinked subreport can also use a different data set from the main report. Figure 2 shows a sales report by country. However, the report requirements specify including a summary by country at the end of the report. The following steps show you how to add the subreport.
Chapter 7: Subreports
151
Figure 2. A sales report totaled by country. 1.
Select Insert | Subreport from the menu or click the Insert Subreport button on the Insert Tools toolbar.
2.
In the Insert subreport dialog box, select Create a subreport and enter “Sales Summary” for the report name. Because this subreport is added directly to the main report, there is no separate Sales Summary.RPT.
3.
Click the Report Wizard button. The Data page of the Standard Report Creation Wizard displays.
4.
Select the Customer table from the Available Data Sources list (see Figure 3). Click Next to display the Fields page.
152
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 3. Select the table for the subreport on the Data page of the Standard Report Creation Wizard. 5.
Select the fields Customer.Country and Customer.Last Year’s Sales (see Figure 4). Click Next to display the Grouping page.
Chapter 7: Subreports
Figure 4. Select fields for the subreport on the Fields page of the Standard Report Creation Wizard. 6.
On the Grouping Page (see Figure 5), select Customer.Country.
153
154
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 5. Select the grouping field on the Grouping page. 7.
Click Next to display the Summaries page (see Figure 6). You can see Crystal Reports already selected Last Year’s Sales field to be summed.
Chapter 7: Subreports
155
Figure 6. Use the Summaries page of the Standard Report Creation Wizard to create summaries for the subreport. 8.
Even though there are more steps in the Wizard, this is the last step you need to do for this example. Click Finish to return to the Insert Subreport dialog box.
9.
Click OK to close the Insert Subreport window and return to the designer. Drag the subreport into the Report Footer section of the main report (see Figure 7). A new tab, reflecting the subreport, is added to the designer.
156
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 7. A view of the designer after adding the subreport. 10. Preview the report. The subreport has details for each detail in the main report. The spec did not call for this. Perhaps it would have been better to cancel out of the Standard Report Creation Wizard and create the report from scratch. You may want to keep this in mind when you create your own subreports. Because we already created the subreport, it’s now easier to modify it rather than create it from scratch. 11. Select the Sales Summary tab in the designer. 12. Remove all the objects from the Group Header and Report Footer bands and the Print Date from the Report Header. 13. Delete the objects in the Details band. Deleting the objects removes column headings. You can add them back or choose to suppress the Details band. 14. Select Last Year’s Sales in the Group Footer and then remove the top and bottom border. 15. Shrink the height of all the bands to minimize white space. 16. Preview the subreport (see Figure 8). The subreport now prints the correct information.
Chapter 7: Subreports
157
Figure 8. The subreport, after adjusting the formatting.
Linked subreports In a linked subreport, the data for the subreport is linked to the data in the main report. To add a linked subreport, use the Link tab of the Insert Subreport window. When you link a subreport, Crystal Reports automatically does several things: •
Adds a parameter field to the subreport. This parameter field passes values from the main report to the subreport.
•
Adds a record selection formula to the subreport. This formula uses the parameter field to select the data for the subreport.
•
Prints in the subreport only the records that meet the selection formula.
The following steps show how to add a linked subreport. 1.
Create a report based on the Customer table in the Extreme Access database. Place the Customer Name, City, and Country fields in the Details band.
2.
Stretch the details band so there is additional white space below these fields. You can optionally insert a new section in the band. You will put the subreport into this area.
158
CrysDev: A Developer’s Guide to Integrating Crystal Reports 3.
Select Insert | Subreport from the menu or click Insert Subreport on the Insert Tools toolbar. The Insert Subreport dialog box displays.
4.
Verify the Create a subreport check box is selected, and then enter “Sales” for the Report Name.
5.
Click Report Wizard to display the Standard Report Creation Wizard.
6.
Select the Orders table from the Extreme database.
7.
Click Next to display the Fields page.
8.
Select the fields Order.Order ID, Orders.Order Date, Orders.Order Amount.
9.
Click Finish to close the Standard Report Creation Wizard and return to the Insert Subreport dialog box.
10. Click the Link tab to display the page (see Figure 9).
Figure 9. Link the subreport data to the main report using the Link tab of the Insert Subreport dialog box. 11. Select Customer.Customer ID from the Available Fields list. The value of this field passes to the selection criteria formula in the subreport.
Chapter 7: Subreports
159
12. Crystal Reports creates a new parameter to use to pass the value. This is shown under Subreport parameter field to use. If you have additional parameters in the subreport, they are available in the drop-down list. This makes it possible for you to create your own parameter field. 13. Verify the Select data in subreport based on field check box is selected and the linking field for the subreport is selected. 14. Click OK to close the window. 15. Put the subreport into the space in the Details band below the fields. 16. Preview the report (see Figure 10) to see the sales for each customer below their entry. You may want to format the data in the subreport so it prints correctly.
Figure 10. Previewing the linked subreport shows the matching sales information for the customer.
On-demand subreports On-demand subreports do not print until you request them. To make an on-demand subreport, select On-demand subreport in the Insert Subreport dialog box (see Figure 1). I changed the unlinked report from earlier in this chapter to be a linked, on-demand subreport. The link displays as a hyperlink when you preview the report (see Figure 11).
160
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 11. An on-demand subreport displays as a hyperlink in the main report. To display the subreport, click the link. A new Preview tab is added to the designer. You can then print the subreport. One important difference between a regular subreport and an on-demand subreport is the data is not saved in an on-demand report. This means to print or preview the on-demand subreport, you must have a connection to the database because the data is queried at the time you request the report.
Updating subreports When you insert a subreport from an existing RPT file, it places a copy of the report in the main report. This means if you update the subreport file, you may need to update the copy of the file in the main report. It is not necessary to update subreports created in the main report. You can update a subreport a number of ways: •
In the designer, right-click the subreport and select Re-import subreport from the shortcut menu. This immediately updates the subreport.
•
Select Re-import When Opening on the Common tab of the Format Editor dialog box (see Figure 12) of the subreport. This automatically re-imports the subreport whenever it is opened in the editor. This setting only affects a single subreport.
Chapter 7: Subreports
161
Figure 12. Select Re-import When Opening in the Format Editor to automatically reimport the subreport when you open it. •
Finally, you can select Re-import Subreport When Opening Reports on the Reporting tab of the Options dialog box (see Figure 13). This is a global setting and affects all subreports.
162
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 13. Select Re-import Subreport When Opening Reports in the Options dialog box to automatically re-import any subreports when you open a report.
Summary Subreports are one of the most powerful features of Crystal Reports. By using subreports you can print related data in a different format or unrelated data on the same report. Remember, though, it is necessary to re-import updated subreports based on existing report files. Updates and corrections to this chapter can be found on Hentzenwerke’s web site, www.hentzenwerke.com. Click “Catalog” and navigate to the page for this book.
Chapter 8: Using Formulas
163
Chapter 8 Using Formulas Crystal Reports provides extensive formula capabilities to enhance the calculations, conditions, and functions you use in a report. In this chapter, you will learn how to utilize these formulas.
Throughout this book, I have talked about formulas. Formulas can perform calculations, conditional branching, formatting, record selection, and more. Crystal Reports 9 also introduces a new type of formula, Custom Functions. Crystal Reports provides a very powerful formula language that allows for calculations, comparison, branching, use of built-in functions, and more. There are several places in Crystal Reports where you can enter formulas, but there are two basic types of formulas. The first causes conditional formatting and printing. To enter a formatting formula, click the formula button where ever it is available. Figure 1 shows the Format Editor. The formula button has a picture of a pencil and the text x + 2. Entering a formatting formula causes the picture on the button to change. For example, the Suppress option’s formula button in Figure 1 has a formula behind it.
164
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 1. Click the formula buttons to enter formatting formulas. When you click a formula button, the Formula Workshop opens. The Formula Workshop is discussed later in this chapter. The second way to enter a formula is by using a formula field. To add a formula field, select Formula Fields in the Field Explorer (see Figure 2) and click the New button.
Chapter 8: Using Formulas
165
Figure 2. Use the Field Explorer to add a new formula field. When you add a new formula field, it prompts you to enter the formula name (see Figure 3), and then you must decide if you want to use the Formula Expert or the Formula Editor to enter the formula.
Figure 3. You must enter a formula name before you create a new formula field.
The Formula Editor Most of the time, you will use the Formula Editor (see Figure 4) to enter a formula. The Formula Editor is just one view of the Formula Workshop. The other view is the Formula Expert (discussed later in this chapter).
166
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Figure 4. The Formula Editor view of the Formula Workshop is where you enter most of your formulas. The Formula Editor is divided into several areas: •
At the top is what looks like a single toolbar, but is actually three toolbars; the General toolbar, the Workshop toolbar, and the Custom Function toolbar. These toolbars are available in both the Formula Editor and Formula Expert views.
•
On the left is the Workshop Tree. The Workshop Tree is available in both the Formula Editor and the Formula Expert views. You can dock the Workshop Tree at either the left or right side of the Formula Workshop. You can also have it undocked and floating on the Crystal Reports design surface by dragging it away from the sides.
•
The second toolbar, the Formula Editor toolbar, is only available in the Formula Editor.
•
Next to the Workshop Tree is the Field Tree. From this tree, you select database fields to include in the formula. You can dock the Field Tree or it can float on the design surface.
•
The middle control is the Function Tree. Functions are discussed later in this chapter. You can dock the Function Tree or it can float on the design surface.
•
The Operator Tree on the right lists the various operators available. Operators are discussed later in this chapter. You can also dock the Operator Tree or it can float on the design surface.
Chapter 8: Using Formulas •
167
The last area is the editor itself. This is where you enter the formula or as you make selections from the different trees, you see items entered automatically for you.
This chapter explains each area.
The General toolbar The General toolbar (see Figure 5) has the following functions corresponding to the buttons, from left to right.
Figure 5. The Formula Workshop’s General toolbar groups the general functions. •
Close—closes the current formula after prompting you to save any changes made to the current formula.
•
New—creates a new formula. Alternatively select the arrow next to the new button to add a new Formula, Custom Function, Formatting Formula, Record Selection Formula, or Group Selection Formula.
•
Rename—allows you to rename the selected formula in the Workshop Tree.
•
Delete—deletes the selected formula in the Workshop Tree.
The Workshop toolbar The Workshop toolbar (see Figure 6) has the following functions, from left to right.
Figure 6. The Workshop toolbar affects how the Workshop Tree displays. •
Hide/Show Workshop Tree—toggles display of the Workshop Tree
•
Expand/Collapse node—expands or collapses the selected node in the Workshop Tree.
•
Show formatting formula nodes only—toggles display of items in the Formatting formulas folder with or without formulas attached.
168
CrysDev: A Developer’s Guide to Integrating Crystal Reports
The Custom Function toolbar The Custom Function toolbar (see Figure 7) has the following functions, from left to right.
Figure 7. The Formula Workshop’s Custom Functions toolbar provides quick-add custom functions to the report or repository. •
Toggle properties display—toggles between the Custom Function editor and the Custom Function Properties dialog box. Custom functions are discussed later in this chapter.
•
Add to Repository—adds the custom function to the Repository.
•
Add to Report—adds the custom function to the report.
The Workshop Tree The Workshop Tree (see Figure 8) shows the available formulas and report objects. To edit one of the formulas, expand the formula category in the tree, and then select the formula you want to edit.
Chapter 8: Using Formulas
169
Figure 8. The Workshop Tree contains the formulas and report objects available to the current report.
The Editor toolbar The Editor toolbar (see Figure 9) provides the following functions, from left to right.
Figure 9. A view of the Editor toolbar. •
Save—saves the current formula. It notifies you if any errors are found in the formula and asks if you still want to save. Alternatively press Alt+S to save the formula.
•
Check—validates the current formula. Alternatively press Alt+C to check the formula.
170
CrysDev: A Developer’s Guide to Integrating Crystal Reports •
Undo—undoes the last change.
•
Redo—reapplies the last undo.
•
Browse Data—displays data from the currently selected field in the Field Tree.
•
Find or Replace—displays the Find dialog box (see Figure 10) to find and Alternatively replace text.
Figure 10. Use the Find dialog box to find and optionally replace specific items in the Formula Editor. •
Toggle Bookmark—toggles a bookmark on or off on the current line of the editor. Alternatively press Ctrl+F2 to toggle a bookmark.
•
Next Bookmark—moves the insertion point to the beginning of the next bookmarked line. Alternatively press Ctrl+Alt+F2 to move to the next bookmark.
•
Previous Bookmark—moves the insertion point to the beginning of the previous bookmarked line. Alternatively press Shift+F2 to move to the previous bookmark.
•
Clear All Bookmarks—removes all bookmarks in the current formula. Alternatively press Ctrl+Shift+F2.
•
Sort Trees—toggles the sorting of items in the Field, Function, and Operator Trees. Alternatively press Ctrl+O.
•
Field Tree—toggles the display of the Field Tree. Alternatively press Alt+F.
•
Function Tree—toggles the display of the Function Tree. Alternatively press Alt+U.
•
Operator Tree—toggles the display of the Operator Tree. Alternatively press Alt+P.
Chapter 8: Using Formulas
171
•
Syntax—selects the syntax language for the formula. You can choose to use Crystal syntax or Basic syntax. These are explained later in this chapter. Alternatively press Ctrl+T.
•
Comment/Uncomment Selected Text—either adds a comment or removes a comment on the selected text in the editor. Alternatively press Alt+M.
•
Use Expert—changes the Formula Workshop to use the Formula Expert instead of the Formula Editor. Alternatively press Alt+X.
The Field, Function, and Operator Trees are explained later in this chapter.
Understanding formulas Crystal Reports formulas are basically short programs. Two formula languages are supported, Crystal syntax and Basic syntax. Basic syntax closely resembles Visual Basic. While you may be more familiar with Basic, it is important you understand both, as you may have to support reports that use Crystal syntax. It doesn’t matter which formula language you choose, just keep in mind you cannot mix languages in a single formula. You set the default formula language on the Reporting tab of the Options dialog box. As you create formulas, you can directly enter the code into the Formula Editor or select fields, operators, and functions from the available lists. You can also use the Formula Expert to walk you through the formula. Lines using Crystal syntax can terminate with a semicolon, but it is not required. However, I recommend you do so, as it makes the code easier to read. Basic syntax terminates a line with a carriage return.
Comments Comments written using Crystal syntax begin with a double slash (//). You can enter a comment on a line by itself or at the end of a line. // This is a comment “Hello” // This is also a comment
Basic syntax comments use an apostrophe. Just like Crystal syntax, the comment can be on a single line or after a statement at the end of a line. ‘ Here is a Basic syntax comment “Crystal Reports rocks” ‘ Another comment
You can also select any number of lines and click the Comment/Uncomment Selected Text button on the Formula Editor toolbar or press Alt+M to comment the highlight text.
Data Types Crystal Reports formulas support several data types. I organized these into three categories: simple, range, and array.
172
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Simple data types Simple data types are the easiest to use. •
Number—basic numbers like 34 or 4.237.
•
Currency—indicated with a dollar sign. For example, $12.34.
•
String—delimit strings with either single or double quotes in Crystal syntax and double quotes in Basic syntax. For example: “Today is Friday.”
•
Boolean—the two values are True and False.
•
Date—defines a specific date. For example, #12/25/2002#, #25 Dec 2002#, and #December 25, 2002# all designate the same date.
•
Time—specify time using the same delimiters as a date. For example, #8:04 pm# and #20:04# both define the same time.
•
DateTime—you can also mix date and time to create a DateTime. For example, #12/25/2002 8:04 pm# or #25 Dec 2002 20:08#.
Range data types Range data types are a bit difficult to understand and look quite strange when you first see them. You use range types to specify a range of values, for example from 5 To 30. You can use ranges with any simple data type except Boolean. The underscore on a range means to exclude the top or bottom number in the specified range. You specify a range using either Crystal or Basic syntax. The range types are: •
To
•
_To
•
To_
•
_To_
•
UpTo
•
UpTo_
•
UpFrom
•
Is =—the same as UpFrom, the preference in Crystal syntax. Is >= is preferred in Basic syntax.
Here are some examples: 5 To 90; // All numbers beginning with 5 and ending with 90 5 _To 90; // All numbers beginning with 6 and ending with 90 5 To_ 90; // All numbers beginning with 5 and ending with 89 5 _To_ 90; // All numbers beginning with 6 and ending with 89 UpTo 90; // All numbers up to and including 90 UpTo 90; // All numbers up to, but excluding 90 UpFrom 90; // All numbers higher than and including 90
You can perform operations on a range using the In keyword to determine if certain values are in the range. 5 In 5 To 10; // Returns True because 5 is in the range from 5 to 10 5 In 5 _To 10; // Returns False because 5 is not in the range from 6 to 10
Array data types Crystal Reports support one-dimensional arrays, which can contain any data type. Using Crystal syntax, you define arrays with brackets and separate each element with a comma. For example: [1, 2, 3, 4, 5]; [“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”]; [#January 1, 2002#, #April 1, 2002#, #July 1, 2002#, #October 1, 2002#];
You reference a particular element of an array by placing the element number in brackets after the array. [5, 10, 15, 20, 25][2]; // Return the second element, which is 10 [5, 10, 15, 20, 25][2 To 4]; // Returns a new array with the second to // fourth elements of the original array, which is [10, 15, 20]
Basic syntax uses regular parenthesis to define an array. (1, 2, 3, 4, 5) (“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”) (#January 1, 2002#, #April 1, 2002#, #July 1, 2002#, #October 1, 2002#)
Referening a particualar element is similar to Crystal syntax: (5, 10, 15, 20, 25)(2) ‘Return the second element, which is 10 (5, 10, 15, 20, 25)(2 To 4) ‘Returns a new array with the second to ‘ fourth elements of the original array, which is (10, 15, 20)
174
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Variables Variables can be of any simple, range, or array data type and have three scoping levels: •
Global—visible through the entire report. This is the default scoping level.
•
Local—visible only in the formula where defined.
•
Shared—visible to the report and any subreports.
Before using a variable, you need to declare its scope and type. // Crystal Syntax Local StringVar Name; Shared DateVar Birthday; Local BooleanVar ReturnValue; Global NumberVar Array Numbers; Redim Numbers [6]; ‘Basic Syntax Local Name As StringVar Shared Birthday As DateVar Dim ReturnValue As BooleanVar Global Numbers() As NumberVar Redim Numbers(6)
Note the use of Dim in the Basic syntax declarations. Dim is the same as Local. Once you declare a variable, you can use it in a formula. Using Crystal syntax, you assign a value to a variable with either an = or a :=. Basic syntax uses just the =. // Crystal Syntax Name := “John Smith”; Birthday := #February 22, 1950#; ReturnValue := True; Numbers := [5 To 9]; Numbers[6] := [10]; ‘Basic Syntax Name = “John Smith” Birthday = #February 22, 1950# ReturnValue = True Numbers = (5 To 9) Numbers(6) = 10
Fields There are several, different types of fields you can use in a formula. Each field type has a different syntax, but each field is enclosed in brackets. The syntax is the same for either Crystal or Basic syntax. You can enter the field directly or drag it from the Field Tree (see Figure 11) into the Formula Editor.
Chapter 8: Using Formulas
Figure 11. You can drag fields from the Field Tree into your formula. Database fields don’t have any special characters. {Customer.Customer ID} {Customer.Name} {Orders.Discount}
Parameter fields use a ? character. {?Country} {?Quarter}
Finally, you can refer to other formulas using the @ character. {@My First Formula} {@My Second Formula}
Operators Operators fall into categories like arithmetic (+, -, *, /), comparisons (>, >=. ), control structures (if, do while), and others. In all, operators fall into 12 categories. •
Arithmetic
•
Conversion
175
176
CrysDev: A Developer’s Guide to Integrating Crystal Reports •
Comparisons
•
Strings
•
Ranges
•
Boolean
•
Arrays
•
Pattern
•
Control Structures
•
Other
•
Scope
•
Variable Declarations
You have already seen some of these such as scope and variable declarations. I will explain some of the others in this section and leave others for your own exploration. You can enter an operator directly or drag it from the Operator Tree (see Figure 12) to the Formula Editor.
Figure 12. You can drag an operator from the Operator Tree into your formula.
Chapter 8: Using Formulas
177
Arithmetic operators Use arithmetic operators to do math. The operators, in order of precedence, are: •
Exponents (^)
•
Negation (-)
•
Multiplication, Division, Percent (*, /, %)
•
Integer Division (/)
•
Modulus (Mod)
•
Addition, Subtraction (+, -)
Comparison operators Use comparison operators to compare one value to another. The comparison operators, in order of precedence, are: •
Equal (=)
•
Not Equal ()
•
Less Than (=)
Boolean operators Boolean operators change the way comparison operators work. The Boolean operators, in order of precedence, are: •
Not (Not)
•
And (And)
•
Or (Or)
•
Exclusive Or (XOr)
•
Logical Equivalents (Eqv)
•
Logical Implication (Imp)
Logical Equivalents compares two logical values and returns true if both are true or both are false. Here are some examples
178
CrysDev: A Developer’s Guide to Integrating Crystal Reports
Local BooleanVar x; Local BooleanVar y; x := true; y := true; x Eqv y; // Returns true x:= false; x Eqv y; // Returns false y := false x Eqv y; // Returns true
Logical Implication returns also compare two logical values. It returns true if both are true or both are false or the second value in the comparison is true. Local BooleanVar x; Local BooleanVar y; x := true; y := true; x Imp y; // Returns true x := false; x Imp y; // Returns false y := false; x Imp y; // Returns true
Control structures Control structures change the way the formula flows. These include branching and looping operators. If/Then/Else The If statement works like the If statement in other programming languages. This example shows how to use If/Then/Else with Crystal syntax. // Return 60% of the salary if employee is in the sales dept. If {Employee.Dept} = “Sales” Then {Employee.Salary} * 0.6 Else {Employee.Salary} * 1.6; // Return an increment of income based on current value of income Global NumberVar Income If Income >= 50000 Then Income + 5000 ElseIf Incomce >= 100000 Then Income + 10000 Else Income;
Chapter 8: Using Formulas
179
Here’s the same example using Basic syntax: ‘ Return 60% of the salary if employee is in the sales dept. If {Employee.Dept} = “Sales” Then {Employee.Salary} * 0.6 Else {Employee.Salary} * 1.6 End If ‘ Return an increment of income based on current value of income Global NumberVar Income If Income >= 50000 Then Income + 5000 ElseIf Incomce >= 100000 Then Income + 10000 Else Income End If
Select The Select statement is similar to the select, switch, or case statements of other programming languages. The first example shows Crystal syntax: Select {Employee.Income} Case 50000 To_ 100000 : Income + 5000 Case UpFrom 100000 : Income + 10000 Default : Income;
The same example using Basic syntax looks like: Select {Employee.Income} Case 50000 To_ 100000 Income + 5000 Case Is >= 100000 Income + 10000 Case Else Income End Select
For/Do For/Do loops a specified number of times. Using Crystal syntax, you have: Local DateVar Holiday := #July 4#; Local StringVar PrintMessage := “”; For i := 1 To 50 Do ( PrintMessage := PrintMessage + “Happy Independence Day! “ ) ;
180
CrysDev: A Developer’s Guide to Integrating Crystal Reports With Basic syntax, the code looks like:
Local Holiday As DateVar Local PrintMessage As StringVar Holiday = #July 4# PrintMessage = “” For i = 1 To 50 PrintMessage = PrintMessage && “Happy Independence Day! “ Next i
Do/While The Do/While loop runs until a condition evaluates to true. // Crystal syntax Do While i