Professional Documents
Culture Documents
20 Secret Shortcuts and Workarounds for Crystal Reports Designers and Developers
This guide is for your personal use, compliments of Business Objects Education Services. It contains a concise summary of answers to the most common Crystal Reports questions, along with links to more detailed explanations. Created to help report designers and developers quickly improve their skills, this guide was: Developed by the people who wrote the code experts who can explain their secrets, step by step Based on the most common questions identified by Technical Support Designed to help you get the most out of Crystal Reports. Learn to unlock the value inside your information to help your organization improve business performance.
..
ii
Contents
Why these secrets are so important i.) Critical skill deficit ..................................................................................... 5 ii) Cost of inadequate preparation ........................................................... 6
iii) Impact on IT project success .................................................................. 7 iv) Training resources available ................................................................... 8
Top 20 Secrets Secrets for Report Designers: #1. How to display every nth record in Crystal Reports ........................ 9 #2. How to display only the report file name on a report ...................11 #3. How to suppress a blank subreport from displaying....................12 #4. How to share subreport data with the main report .......................15 #5. Evaluate null field values in formulas or record selection ..........18 #6. How different 'Keep Together' options affect the report .............23 #7. How to export to PDF or RTF in Crystal Reports............................28 #8. Suppress a section that contains a blank subreport ....................30 #9. How to create a table of contents for a report ...............................39 #10. How to add time fields .........................................................................43 #11. What font types are supported in Crystal Reports? ....................47 #12. How to format specific words or characters within a string ......50 #13. How to display a date range parameter on a report ....................52 #14. How to suppress a blank subreport .................................................54
iii
Contents
Secrets for Developers: #15. How to deploy an application that uses Crystal Reports and VS .NET...............................................................56 #16. What is Unicows.dll and where can you find it? ..........................59 #17. How to change the data source using CR for VS .NET application ......................................................60 #18. How to pass Database logon info to a Crystal Report at runtime in VB .NET .......................................65 #19. How to create a report and add a parameter field using Report Creation API .................................70 #20. Crystal Reports for Visual Studio .NET............................................76
iv
42% no end-user training beyond that provided at the end of the implementation
Source: Meta Group research, August 2003 as cited in ZD Net online article Three out of four ERP users raise the white flag.
Fact: Preparation and skill development are key project success factors
The impact of inadequate preparation may be greater than you think. We all suffer from the tyranny of the urgent putting off learning critical skills even though we will desperately need these very skills in the middle of a demanding project. Here is the question: What is the cost of failure or delay on your project?
Why do IT Projects fail? Incomplete Requirements 13.1% Lack of User Involvement 12.4% Lack of Resources 10.6% Unrealistic Expectations 9.9% Lack of Executive Support 9.3% Changing Requirements & Specifications 8.7% Lack of Planning 8.1% Didnt Need it any longer 7.5% Lack of IT Management 6.2% Technology Illiteracy 4.3%
Applies to:
Reported version and lower Formulas Conditional Suppression Format Section
Synopsis:
In Crystal Reports (CR), is it possible to display every nth record without indexing the database table? For example, you have a report with 100 records but you only want to see every 25th record. Your report connects to a database table that does not contain an indexed field.
Solution:
A formula can be created that will display every nth record by conditionally suppressing all other records. The example below shows how to display every 25th record.
Example Formula:
Remainder((recordnumber),25) <> 0 You will employ this formula in the Section Expert. To apply this formula in the Section Expert: 1. Right-click on the details section and click 'Section Expert'. 2. On the 'Sections' list, click the details section. 3. Leave the check box cleared and click the 'X+2' command button next to 'Suppress (No Drill-Down)'. The formula editor opens.
4. Type the formula provided by this article. 5. Save your formula and close the formula editor. 6. Click OK in the Section Expert. You will now only see every 25th record. All other records do not display on the report because of the conditional suppression at the details level.
Background Information
This formula returns a value of true for all records not divisible by 25 and a value of false for all records that are divisible by 25. CR reads the results of the formula to determine if a record will appear.
More Information For more information about the 'Remainder' function or 'Record Number' special field, refer to the Crystal Reports Online Help by pressing the 'F1' key. Training:
Learn more about Crystal Reports - Report Design. Refer to 'Courses & Schedules' at:
http://www.crystaldecisions.com/training
10
# 2 How to display only the report file name on the report http://support.businessobjects.com/library/kbase/articles/c2015683.asp
Applies to:
All versions Formulas Return File Name
Synopsis
When using the special field called 'filename' the report shows the entire path including the file name. How do you display just the report file name on the report?
NOTE: The report must be saved before the formula will return a value, or it will return an empty string. This formula is not version-specific and can be placed in any report, because it uses the special field 'filename', which exists in Crystal Reports 8.5, 9, and 10.
Solution
To display just the report file name on a report, use a formula similar to this:
@ReportFileName: //This is the formula name StringVar Array File:=Split(filename,'\'); NumberVar i := Ubound(File); File[i];
Training:
Learn more about Crystal Reports - Report Design. Refer to 'Courses & Schedules' at:
http://www.crystaldecisions.com/training
11
Applies to:
Reported version and lower Hiding subreports that have no records Using 'Suppress Printing if No Records' checkbox
Synopsis
NOTE: New to Crystal Reports 9 is the 'Suppress Blank Subreport' check box. For more information on how to suppress blank subreports in CR 9, refer to our knowledge base article c2011893.
How can you suppress a blank subreport from displaying on the main report. Moreover, you want to suppress the sections within a subreport, if there is no data, so that it does not display on the main report?
For example:
There is a subreport contained in the main report. If the subreport does not contain any data, you do not want it to display in the main report. You want to suppress the sections of the blank subreport.
Solution
NOTE: This workaround applies to Crystal Reports 8.5 and earlier.
A subreport is an object within the Crystal Reports designer. Since the subreport is inserted into the main report, it cannot be entirely suppressed. Even when a subreport does not have any records, the subreport object still exists within a section of the main report. This means the Crystal Reports designer does not consider a section that contains a subreport as a blank section. You notice that by selecting the 'Suppress if blank' option, from the 'Section Expert' does not work. To workaround this, you must first suppress the blank subreport, then shrink the blank section.
12
This only suppresses the subreport from printing, so you will not see the contents of the subreport; the subreport still exists as an object in the main report. This means you still cannot format the main report section that contains the blank
1. In the main report, right-click the subreport object and click 'Edit Subreport'. This takes you to the 'Subreport' tab of the main report. 2. On the 'File' menu, click 'Report Options'. 3. Select the 'Suppress Printing if No Records' checkbox, and then click 'OK'. 4. Return to the 'Preview' tab of the main report. 5. Refresh the report. Blank subreports now appear as empty boxes on the report.
13
Now when you preview the main report, the blank subreports are hidden from view.
CAUTION: If you want to actually suppress the section in the main report that contains the blank subreport, instead of merely concealing the blank subreport on the main report, refer to knowledge base article c2005853. Keep in mind, however, that the solution in knowledge base article c2005853 requires inserting another subreport, which will significantly increase the time it takes to process and display your report.
Training:
Learn more about Crystal Reports - Report Design. Refer to 'Courses & Schedules' at:
http://www.crystaldecisions.com/training
14
Applies to:
Reported version and higher Shared variables Passing data between subreport and main report
Synopsis
A report contains a subreport. Data from the subreport is required for calculations in the main report. How can you share subreport data with the main report in version 7 (or higher) of the Crystal Reports Designer?
Solution
Shared variables, introduced in Crystal Reports version 7, make it easier to pass values from a subreport to the main report. Using shared variables requires two formulas: one to store the value in a shared variable, the other to retrieve the value from the shared variable. The most important thing to remember when using shared variables is that Crystal Reports must first evaluate the formula where the value is stored before evaluating the formula that retrieves the shared variable. For example if you want to pass a grand total from the subreport to do a calculation in the main report, follow these steps: 1. In the subreport, create a formula similar to the one below:
//@SubFormula //Stores the grand total of the //{Orders.Order Amount} field //in a currency variable called 'myTotal'
15
2. Place this formula in your subreport. 3. In the main report, create a formula that declares the same variable name:
//@MainFormula //Returns the value that was stored //in the shared currency variable called //myTotal in the subreport WhilePrintingRecords; Shared CurrencyVar myTotal; myTotal
4. Place @MainFormula in a main report section that is beneath the section containing the subreport. For the shared variable to return the correct value in the main report, you must place @MainFormula in a main report section that is beneath the section containing the subreport. This ensures Crystal Reports evaluates the @SubFormula before @MainFormula. One way to do this is to insert a section below the section containing the subreport, and place @MainFormula in this new sub-section: On the 'Format' menu, click 'Section'. On the 'Sections' list, click the section containing the subreport. Click 'Insert' (at top of dialog box). This inserts an additional subsection. Click 'OK' to return to the report, and insert @MainFormula into this new subsection. The next time you preview the report, @MainFormula displays the value from the subreport. In this particular example, that value was the grand total of the {Orders.Order Amount} field.
16
5. Once you have verified that @MainFormula is returning the correct value from the subreport, you can include this formula in other main report formulas, such as:
//@NewFormula //includes data from subreport {@MainFormula}+ Sum ({Customer.Last Year's Sales})
Place this formula in the same section as @MainFormula, or in a section further down on the report. You have now successfully shared data from a subreport with the main report.
Training
Learn more about subreports in the Crystal Reports - Report Design III training course. Refer to 'Courses & Schedules' at:
http://www.businessobjects.com/training
17
#5 How to evaluate null field values in formulas or record selection criteria http://support.businessobjects.com/library/kbase/articles/c2010914.asp
Applies to:
All versions Record selection criteria Formula displays unexpected results IsNull function
Synopsis
A database field contains values and null values. In Crystal Reports (CR), when previewing the report, a list of values and blank values appears in the Details section. How can you evaluate this database field in formulas or record selection criteria to return the expected result set?
Example Scenario
1. Add a Number field, {YourDatabaseTable.NumberField}, to the Details section of the report. Field values contained in the database 1 <Null> <Null> 2 3 Field values that appear in CR 1 <blank space> <blank space> 2 3
NOTE: The <blank space> in CR represents the null values from the database field.
18
2. Add the following record selection criteria to the report: {YourDatabaseTable.NumberField} < 3
3. Upon adding the record selection criteria, the values that appear on the report are not what you expected. Expected field values based on record selection criteria 1 <blank space> <blank space> 2 Field values that appear in CR based on the record selection criteria 1 2 Why do the null values not appear in the result set based on the record selection criteria? How can you evaluate the null values in the Number field to return the expected result set? Why do blank values or incorrect values appear in the result set of a formula?
Solution
The expected result set does not appear because the example of record selection criteria does not evaluate the null values. Null values in the Number field are not evaluated as zero (0) values by default. In CR, to evaluate fields that contain null values to return the expected result set, use one of the following solutions:
Option A) Convert the null value to the default value of their data type.
EXAMPLE DEFAULT VALUES BY DATA TYPE * The null values in a Number field are converted to a zero (0) number value. * The null values in a String (Text) field are converted to an empty string ("") value. 19 Business Objects Crystal Reports Secrets
* The null values in a Date field are converted to zero (0, 0, 0) date values. * The null values in a Date-time field are converted to zero (0, 0, 0, 0, 0, 0) date-time values.
- OR Option B) Evaluate the null value within record selection criteria or within formulas using the IsNull function.
Follow the steps below for A) or B) to evaluate null values to return the expected result set. Also, with regards to the related issue, blank values or incorrect values appear because the formula includes a database field that contains null values. Follow the steps below for A) or B) to correctly evaluate the null values to return the expected result set.
A) STEPS TO CONVERT NULL FIELD VALUES TO DEFAULT VALUE FOR ALL FIELDS IN CR
1. Click File > Report Options 2. Select the 'Convert NULL Field Values to Default' check box.
NOTE: The IsNull function evaluates the database field(s) for null values. It is important to evaluate every database field included in the formula or record selection criteria for null values.
3. Click 'OK'. Selecting 'Convert NULL Field Values to Default' affects all database fields on the report. CR is now able to successfully evaluate any null or blank values contained in the database fields according to the default value of their data type.
20
c) Evaluate for null values in a String or Text field //This formula evaluates if the String field contains null records. Additionally, the Trim //formula function is used to account for a blank space caused by pressing the Space Bar.
WhilePrintingRecords; Stringvar Message; If IsNull({YourDatabaseTable.StringField}) or Trim({YourDatabaseTable.StringField}) = "" Then Message := "Your Message" Else Message := {YourDatabaseTable.StringField}
Upon completing the above steps, CR will successfully evaluate null field values in a formula or record selection criteria to return the expected result set.
Background information
If the 'Convert Null Field Values to Default' check box is not selected or if the database field has not been evaluated using the IsNull function, the following behavior occurs in CR when a null value is encountered: * Formulas or record selection criteria stop evaluating the null value. For example, if the 21 Business Objects Crystal Reports Secrets
formula is incrementing a value based on the database field, the value does not increment nor does the remainder of the formula continue to evaluate. However, the formula continues on to evaluate the next record. * Formulas or record selection criteria return a blank value. If the formula's calculations are based on the field values, it is possible to return incorrect values.
Training:
Learn more about additional functions in the Crystal Reports - Report Design II training course. Refer to 'Courses & Schedules' at: http://www.crystaldecisions.com/education
22
Applies to:
Reported version and lower Keep Group Together Keep Columns Together Keep Object Together
Synopsis
In the Crystal Reports (CR) Designer, how do the different 'Keep Together' options affect the report? The 'Keep Together' options in CR are as follows: * Keep Together * Keep Group Together * Keep Object Together * Keep Columns Together Where do you find the 'Keep Together' options in CR and how do they affect your report?
Solution
The 'Keep Together' options are available to format objects and sections of the report. The 'Keep Together' options affect how the report displays the particular object or section. Based on the report sections and commonly used report objects, this article provides the following: * Where to find the 'Keep Together' options * Example report details * How the report is affected based on the example report details Report sections and commonly used report objects that include the 'Keep Together' 23 Business Objects Crystal Reports Secrets
options: A) Report Header/Report Footer, Group Header/Group Footer, Details B) Group Options C) Subreports, Text Objects, Ole Objects, And Other Database Fields D) Cross-tabs
NOTE: 'Keep Together' is unavailable for the Page Header and Page Footer sections. This is by design. Each Page Header and Page Footer is already designed to keep together at the top and bottom of each page. NOTE: Do not use this option if your intention is to keep the entire group together. Use the 'Keep Group Together' option as described in B)
24
2. In the Section Expert, select the section. 3. Under the Common tab, select 'Keep Together' check box. When the 'Keep Together' option is selected, CR keeps the entire instance of the particular section on the same page.
B) GROUP OPTIONS
To locate the 'Keep Group Together' option for inserting or changing a group, follow these steps:
NOTE: If the group instance spans multiple pages, 'Keep Group Together' option starts on a new page and continues through the multiple pages until the particular group instance is completed. If more than one group instance can fit on one page, more than one group instance will display on the same page. Do not use this option if the intended purpose is to have each group start on a new page. If the intended purpose is to have each group start on
1. Click the following options depending on whether you are inserting a new group or changing an existing group: * Insert > Group for inserting a new group * Report > Change Group Expert > Options for changing an existing group 2. Under the "Group Options" heading, select the 'Keep Group Together' check box. 3. Click 'OK'.
25
3. Under the Common tab, select the 'Keep Object Together' check box. When the 'Keep Object Together' option is selected, CR keeps the entire instance of the particular object on the same page.
D) CROSS-TABS:
To locate the 'Keep Columns Together' option for formatting a cross-tab, follow these steps: 1. Right-click the cross-tab. 2. Select 'Format Cross-tab'. 3. Under the Customize Style tab, select the 'Keep Columns Together' check box. When the 'Keep Columns Together' option is selected, CR keeps the columns together if a column width spans across to a second page.
selected, the columns that would span across the edge of the pages start on a new page. A cross-tab column is not divided between two pages.
Training
Learn more about object and section formatting options in these courses: Crystal Reports - Report Design I Crystal Reports - Report Design II Refer to 'Courses & Schedules' at:
http://www.businessobjects.com/training
27
Applies to:
Reported version and lower Report Design Exporting to PDF and RTF
Synopsis
Can I export my report to Adobe Acrobat PDF (Portable Document Format) or RTF (Rich Text Format) from the Crystal Reports report designer? If so, how?
Solution
Crystal Reports 8.5 and later allows exporting to PDF. Exporting to PDF in Crystal Reports 8 and earlier is not supported. Crystal Reports 8 and later allows exporting to RTF. Exporting to PDF or RTF in Crystal Reports 8.5 retains the best WYSIWYG (What-yousee-is-what-you-get) format of the original report. Exporting to PDF and RTF in Crystal Reports 8.5 support many features that other exporting formats cannot.
Export to PDF
NOTE: This export DLL is designed to work with Adobe Acrobat
1. On the 'File' menu, click 'Export'. 2. In the 'Export' dialog box, click 'Acrobat Format (PDF)' from the 'Format' drop-down box. 3. Click the destination of your choice from the 'Destination' drop-down box. (To save to a file on your computer, click 'Disk file'.) 4. Click 'OK'.
28
Export to RTF
1. On the 'File' menu, click 'Export'. 2. In the 'Export' dialog box, click 'Rich Text Format' from the 'Format' drop-down box. 3. Click the destination of your choice from the 'Destination' drop-down box. (To save to a file on your computer, click 'Disk file'.) 4. Click 'OK'.
More Information
For information on troubleshooting errors exporting to PDF and RTF refer to our knowledge base article c2012282. For information on ALL the formats that Crystal Reports has exporting functionality to, download the applicable document. For Crystal Reports version 7 - SCR7ExportLimitations.zip For Crystal Reports version 8 - SCR8_ExportLimitations.zip For Crystal Reports version 8.5 - cr85_exportlimitations.zip For Crystal Reports version 9 - cr9_exportlimitations.pdf These documents also list all supported and unsupported exporting features in Crystal Reports 7, 8, and 8.5.
http://www.businessobjects.com/training
29
Applies to:
Reported version and lower Seagate Info Blank Subreports Conditional Suppression
Synopsis
In Crystal Reports (CR) 8.5 and earlier, how do you suppress a section in the main report that contains a blank subreport? For example: A subreport is placed in the group header of the main report. You notice that if the subreport does not return data the group header contains a blank space the size of the subreport. You want to suppress the group header of the main report when the subreport is blank.
Solution
NOTE: New to Crystal Reports 9 is the 'Suppress Blank Subreport' check box. For more information on how to suppress blank subreports in CR 9, refer to our knowledge base article c2011893.
30 The group header that contains the blank subreport does not shrink because the subreport is an object within the Crystal Reports designer. A section containing a subreport is never blank even if the subreport is because it contains a subreport object. You notice that by selecting the 'Suppress if blank' option, from the 'Section Expert' does not work. This knowledge base article provides a solution to suppress a section that contains a blank subreport for CR 6, 7, 8 and 8.5. The following procedures must be completed in order to achieve the desired results: creating a duplicate subreport placement of a duplicate subreport Business Objects Crystal Reports Secrets
creating a formula to test if the subreport is blank conditionally suppressing a section that contains original subreport minimizing a duplicate subreport and resizing the section
NOTE: You must create another subreport based on the original subreport. To create a duplicate subreport, complete the following steps: 1. From the main report in CR, rightclick the subreport. 2. From the fly-out menu, select 'Save Subreport As'. 3. Provide a name for the duplicate subreport and click 'Save'. Placement of a Duplicate Subreport
31
8. Click 'OK'. The duplicate subreport will be attached to the cursor. 9. Insert the subreport in the new section (such as group header b from step 2). 10. In the main report, on the 'Edit' menu click 'Subreport Links'. The top drop-down box will contain both the original and duplicate subreports. Compare these two subreports and enure that the fields in the 'Filed(s) to link to' box are the same. Also, check that the parameter in the bottom-left drop-down box and the field in the bottom-right dropdown box are the same.
32
7. From 'Line style', select 'None' for Left, Right, Top, Bottom. 8. Select the main report. 9. Resize the section that contains the duplicate subreport to be as small as possible.
Crystal Reports 6
Before you begin this process, you will need to download uflstore.zip from our website at: http://support.crystaldecisions.com/downloads The reason you need to obtain this file is because shared variables were introduced in Crystal Reports 7. In order to suppress a section that contains a blank subreport in Crystal Reports 6, you will need to use the store and fetch function. To suppress a section that contains a blank subreport in Crystal Reports 6, complete the following:
34
For example, f the subreport is located in the group header, right-click the left gray margin at the group header level. 2. From the fly-out menu, select 'Insert Section Below'. You notice another section is inserted into the report labeled 'b'. For example, by inserting another group header you notice that there is group header A and group header B. 3. Select the original subreport, drag and drop it into the second section. 4. Insert the duplicate subreport by selecting 'Subreport', from the 'Insert' menu. 5. Select 'Choose a report', from the 'Insert Subreport' dialog box. 6. Browse to find the duplicate subreport. 7. Select the report and click 'Open'. 8. Click 'OK'. The duplicate subreport will be attached to the cursor. 9. Insert the subreport in the new section (such as group header b from step 2). 10. In the main report, on the 'Edit' menu click 'Subreport Links'. The top drop-down box will contain both the original and duplicate subreports. Compare these two subreports and enure that the fields in the 'Filed(s) to link to' box are the same. Also, check that the parameter in the bottom-left drop-down box and the field in the bottom-right dropdown box are the same.
3. Select 'Formula Fields' and select the 'New' icon. 4. Type a name into the 'Formula Name' box and click 'OK'. For example, CheckForNull. This launches the formula editor. 5. Create a formula similar to the following: // @CheckForNull Whileprintingrecords; If IsNull(Count(Table.field)) or Count(Table.field) = 0 then StoreBooleanVar ("Suppress", True) else StoreBooleanVar("Suppress", False) 6. Place @CheckForNull in the Report Header of the duplicate subreport.
36
37
Training:
Learn more about subreports in the Crystal Reports - Report Design III training course. Refer to 'Courses & Schedules' at:
http://www.crystaldecisions.com/training
38
Applies to:
Reported version only Table of Contents Subreports Add Command
Synopsis
In Crystal Reports (CR) 9, is it possible to create a table of contents at the beginning of a report? A table of contents would be in the Report Header, showing group names next to the page numbers the groups start on.
Solution
You can make a table of contents using a subreport with a command object. Using a command object it is possible to write to a database from CR. The following example will use a subreport to write group names and page numbers to a new table in your database. WARNING: Crystal Reports is not recommended as a tool to write to, update or delete from a database. Database clients or applications designed specifically to edit databases should be used instead. However, now that CR has full SQL functionality it is possible to write to, update and delete from databases. This article is provided as a tip. Before attempting to implement the steps in this article, consult your Database Administrator (DBA). Your DBA needs to grant specific rights to your database.
39
40
NOTE: This SQL Query (and any other SQL syntax in this article) is written for a Microsoft SQL Server database. Consult the database manual or Database Administrator for the correct syntax for your data source. Business Objects Technical Support does not provide support for writing SQL queries, as they are database specific.
8. In the 'Add Command to Report' dialog box enter a SQL Query similar to the following:
{?LinkReceiver} DELETE FROM "TableOfContents" WHERE "TableOfContents"."DateTime" <> {?DateTime}; SELECT * FROM "TableOfContents"
This command object will add new GroupName and PageNumber data to the TableOfContents table and delete any existing data based on the ?DateTime parameter. 9. Insert the Grouper and the Page fields in the subreport Details section. Suppress all of the subreport sections. 10. Insert the 'UpdateTOC' subreport in the Report Footer B (RFb) section. (This is to ensure that the formula used to link the subreport is processed before the subreport is processed.) 11. Right-click the 'UpdateTOC' subreport, and then click 'Format Subreport'. Click the 'Border' tab, and then click 'None' from the 'Left', 'Right', 'Top' and 'Bottom' drop-down boxes. Click 'OK' to close the 'Format Editor' dialog box. 12. In the main report, create a formula named 'DateTime' with the following syntax:
CurrentDateTime
13. Insert this formula in the main report's Report Header section. 14. Create another formula named 'LinkMaker' with the following syntax and place it in the Group Header section of the main report:
WhilePrintingRecords; StringVar link; If Not InRepeatedGroupHeader Then link := link & "INSERT INTO TableOfContents VALUES ('" & GroupName ({Product.Product Name}) & "'," & ToText(PageNumber,0) & ",'" & ToText({@DateTime}, "yyyy-MM-dd HH:mm:ss") & "')" & chr(10); link
41
15. Create another formula named 'LinkPasser' with the following syntax and place it in the Report Footer A (RFa) Section of the main report:
WhilePrintingRecords; StringVar link; link
16. In the main report, in the 'Edit' menu, click 'Subreport Links'. In the 'Subreport Links' dialog box click the 'UpdateTOC' subreport from the 'For subreport' drop-down box. 17. Click the '@DateTime' Formula field from the 'Available Fields' box and move it to the 'Field(s) to link to' box. In the 'Subreport parameter field to use' drop-down box, click the '?DateTime' parameter. 18. Repeat step 15, connecting the '@LinkPasser' Formula field to the '?LinkReceiver' parameter. Click 'OK' to close the 'Subreport Links' dialog box. 19. In the 'Field Explorer' of the main report, click 'Special Field'. Insert the 'PageNofM' field in the Page Footer. 20. Preview the report to write the Table of Contents data to the database.
NOTE: If changes are made to the report that affect the page numbering, refresh the report twice to update the TableOfContents table. If the number of pages used by the Table of Contents changes, the report must be refreshed a third time to update the
21. Refresh the report again and the Table of Contents will display the group and page number values based on your report.
Training:
Learn more about Crystal Reports - Report Design. Refer to 'Courses & Schedules' at:
http://www.crystaldecisions.com/training
42
Applies to:
Reported version and higher summing time fields converting seconds to hours, minutes, seconds
Synopsis
The report contains a time field that displays in hh:mm:ss format. How do you create a formula in Crystal Reports (CR) that adds more than one time field and displays the total in the same format: hh:mm:ss? For example: 1:45:01 + 1:45:01 should display 03:30:02 and not 2:90:02
Solution
In order to get the sum of more than one time field and to display the total of the time field in the same format (hh:mm:ss) you must complete the following steps: 1. Convert all the time fields to a common time unit such as seconds 2. Calculate the total time in seconds 3. Convert the seconds back to hh:mm:ss format.
2. To convert the datetime field to seconds, create a formula similar to the following:
local numbervar hours; local numbervar minutes; local numbervar seconds; // Convert the hours to seconds by multiplying by // 3600 hours := hour({@time}) * 3600; // Convert the minutes to seconds by multiplying by // 60 minutes := minute({@time}) * 60; seconds := second({@time}); //add up all the seconds hours + minutes + seconds;
To convert the string field, with the format of hh:mm:ss to seconds create a formula similar to the following: 1. Create a new formula and call it @ConvertTimeStringToSeconds 2. Create a formula similar to the following to convert the string field to seconds:
local numbervar hours; local numbervar minutes; local numbervar seconds; // Parse out the hours portion of the string and // multiply by 3600 to convert to seconds hours := tonumber({timestringfield}[1 to 2])* 3600; // Parse out the minutes portion of the string and // multiply by 60 to convert to seconds minutes := tonumber({timestringfield}[4 to 5]) * 60; // Parse out the seconds seconds := tonumber({timestringfield}[7 to 8]); // Add up all the seconds hours + minutes + seconds;
44
Create a summary formula that will sum the @ConvertTimeToSeconds or @ConvertTimeStringToSeconds 1. Create a new formula and call it @TotalSeconds 2. To sum up either formula, create a formula similar to the following: sum(@ConvertTimeToSeconds, Group) - OR sum(@ConvertTimeStringToSeconds, Group)
45
Training:
Learn more about Crystal Reports - Report Design. Refer to 'Courses & Schedules' at:
http://www.crystaldecisions.com/training
46
#11 What font types are supported in Crystal Reports http://support.businessobjects.com/library/kbase/articles/c2011820.asp The information in the article refers to:
Crystal Reports 9
Applies to:
Reported version and higher Supported exporting fonts TTF Exporting to PDF
Synopsis
For Crystal Reports (CR), this knowledge base article answers the following questions regarding embedded fonts: a) What font types can be displayed within Crystal Reports? b) What font types are supported when exporting to PDF? c) How do you verify the embedded security level of a font?
Solution
a) The following font types can be displayed within Crystal Reports: True Type Fonts (TTF) True Type Collection (TTC) Printer Font Metrics (PFM) Adobe Font Metrics (AFM) Printer Font Binary (PFB) Printer Font ASCII (PFA)
NOTE: Font File Names (FONT) is a font type that is not supported by Crystal Reports
47
b) The following font types are supported when exporting to PDF: True Type Fonts (TTF) True Type Collection (TTC) When exporting a report that contains a font type other than TTF or TTC to PDF format, the font is not successfully exported or the following error message appears: Business Objects Crystal Reports Secrets
"<Font name> cannot be found." c) To verify the embedded security level of a font, review the font properties. If the security level contains "No-embedding" permissions, then exporting to PDF will not be successful. True Type Fonts (TTF) has embedding permissions that determine if they can be converted into an embedded font format. The permissions associated with the embedded security level of a font are as follows: No-embedding - This does not allow fonts to be embedded. Contact the font vendor to request a possible upgrade to an embeddable font. Print and preview - This allows fonts to be embedded. However, only within pages that remains static on the client computer. If a page allows fonts to be changed, then editable or installable fonts are required. Examples of a page that allows fonts to be changed are an online Java-based word processor or an email editor. Editable - This allows fonts to be embedded using a tool such as Microsoft Web Embedding Fonts Tools (WEFT) beyond the limitations of the "Print and preview" permissions. Installable - This allows fonts to be embedded similar to the "Editable" permissions. Note that installable fonts are not installed in the visitors' fonts folder.
NOTE: For the utility to allow you to view the embedded security level of a font, download the "Font properties extension" from Microsoft's web site at: www.microsoft.com /typography
Summary
Not all fonts that can be displayed in Crystal Reports are supported when exporting to PDF. Since PDF format embeds fonts, the font types that are exported must allow embedding. Embedding permissions are determined by the font vendor.
48
Background Information
New to version 9, Crystal Reports supports Unicode. Therefore, double-byte characters can be displayed in Crystal Reports. Also, support for exporting embedded fonts is new to Crystal Reports 9.
More Information
Search for "Embedding Fonts" or "About Font Embedding" on the Microsoft support site at: http://support.microsoft.com Search for "Font Format Types" or "Font File Formats" on the Adobe support site at: http://support.adobe.com
Related Information
Search for the file name, Scrprinterdependency.pdf, on our support site at: http://support.crystaldecisions.com/docs Search for the knowledge base articles, c2011114 and c2010555, on our support site at: http://support.crystaldecisions.com/kbase
Training:
Learn more about Crystal Reports - Report Design. Refer to 'Courses & Schedules' at:
http://www.crystaldecisions.com/training
49
Applies to:
Reported version and higher Formatting fields Word or character formatting HTML
Synopsis
In Crystal Reports (CR) there is no option to format occurrences of a specific word or character, for example, bold or underline, within a string field. How can you format occurrences of a specific word or character within a string field?
Solution
To format occurrences of a specific word or character within a string field, use the 'Replace' function in a formula to replace the word or character. For example, to bold all occurrences of the word "City' in the Customer Name field of the Xtreme sample database, use this formula:
//@boldcity //This is the formula name
NOTE: Word or character formatting is limited to the supported HTML tags. A list of supported HTML tags can be found in the on-line help files by pressing F1.
Place this formula field on the report instead of the database field 'Customer Name' and then select HTML Text Interpretation for the paragraph format as follows: 1. Right-click the formula field and click the 'Paragraph' tab in the Format Editor. 2. In the 'Text interpretation' list, click 'HTML Text'. 3. Click 'OK' to close the Format Editor.
50
Training:
Learn more about fonts in Crystal Reports. Refer to 'Courses & Schedules' at:
http://www.crystaldecisions.com/training
51
Applies to:
Reported version and higher Parameter fields Date range selection formulas in version 5, 6, & 7 Displaying the date range in a report
Synopsis
A report uses parameter fields to prompt you for a start and end date. These dates are then used in the report's record selection formula. To display the date range for this report, a formula similar to the example below is placed in the Report Header:
//{@DateRange} WhilePrintingRecords; DateVar date1; DateVar date2; date1:=Minimum ({Datefield}); date2:=Maximum ({Datefield}); "my selection is: " + totext(date1) + " " + totext(date2)
However, when entering a date that is not in the database, this formula returns confusing results. For example: The database contains date values from November 3rd (11/3/97) to November 30 (11/30/97). If you enter '11/1/97' as the start date, and '11/30/97' as the end date, the @DateRange formula in the Report Header displays "11/3/97 - 11/30/97". This happens because there are no records for November 1st and 2nd. How can you resolve this issue?
52
Solution
NOTE: In Crystal Reports version 7 or higher, you can create ranged parameters. This means that instead of creating both a start and end parameter, you only need one date parameter, which prompts for the start AND end dates. To learn how to use ranged parameters, please consult chapter on parameters in the Crystal Reports User Guide: Chapter 16 of the CR version 7 User Guide Chapter 22 of the CR version 8 User Guide.
To display a parameter-based date range for a report, regardless of whether thos dates are in the database, use text objects. Using Text Objects to Display Date Range: 1. On the 'Insert' menu, click 'Text Object'. Place the text object in the Report Header. 2. On the 'Insert' menu, click 'Parameter fields'. This opens the 'Parameter fields' tab of the 'Insert fields' dialog box. 3. Click the Start Date parameter and insert it into the text object. 4. Press the spacebar to insert a space in the text object, then type the string "to" (without the quotes). 5. Go back to the 'Insert fields' dialog box to insert the End Date parameter into the text object, after the string 'to'. The text object now appears similar to this: [{?pm-startdate} to {?pm-enddate}] This displays the date range that was entered for this report.
Training:
Learn more about Crystal Reports - Report Design.
Refer to 'Courses & Schedules' at: To display the date range using Range Parameters, please see http://www.crystaldecisions.com/training Knowledge Base article C2002512
53
Applies to:
Reported version and higher 'Suppress Blank Subpreport' option Displaying subreports Suppress blank section
Synopsis
In Crystal Reports (CR) 9, how is a subreport suppressed if it contains no data? Also, how is a section suppressed if it contains a blank subreport?
Solution
To suppress a blank subreport, select the 'Suppress Blank Subreport' check box. This feature is new to version 9 of Crystal Reports. To suppress a section that contains a blank subreport, select the 'Suppress Blank Section' check box.
54
Upon selecting the 'Suppress Blank Subreport' and 'Suppress Blank Section' check boxes, the subreport and section will not display on the main report when no data is contained in the subreport.
Background
In Crystal Reports 8.5 and earlier, a blank subreport cannot be suppressed. The blank subreport is recognized as an object in the section. Therefore, a section containing a blank subreport cannot be suppressed. For more information on how to workaround this issue in CR 8.5 and earlier, refer to our knowledge base article c2005853.
Training:
Learn more about subreports in Crystal Reports. Refer to 'Courses & Schedules' at:
http://www.crystaldecisions.com/training
55
#15 How to deploy an application that uses Crystal Reports and VS .NET
#15 How to deploy an application that uses Crystal Reports and VS .NET? http://support.businessobjects.com/library/kbase/articles/c2013175.asp
Applies to:
Reported version only Application Deployment Runtime Files
Synopsis
How do you deploy an application that uses Crystal Reports and Visual Studio .NET?
Solution
Before you deploy an application that uses Crystal Reports and Visual Studio .NET you must confirm the version of Crystal Reports being used with Visual Studio .NET. The possible versions are: - Crystal Reports for Visual Studio .NET 2002 - Crystal Reports for Visual Studio .NET 2003 - Crystal Reports 9 - Crystal Reports 10 To do this, check the assembly version of the Crystal Reports managed components. The Crystal Reports managed components include: - CrystalDecisions.CrystalReports.Engine - CrystalDecisions.Shared - CrystalDecisions.Reportsource - CrystalDecisions.Web - CrystalDecisions.Windows.Forms. In your Visual Studio .NET 'Solution Explorer', expand 'References', right-click on a Crystal Reports managed component, select 'Properties' and check the version property. The assembly version must be the same for all the Crystal Reports managed components referenced in the solution. If your Crystal Reports managed assemblies are version 9.1.3300, your application uses Crystal Reports for Visual Studio .NET 2002.
56
#15 How to deploy an application that uses Crystal Reports and VS .NET
If your Crystal Reports managed assemblies are version 9.1.5000, your application uses Crystal Reports for Visual Studio .NET 2003. If your Crystal Reports managed assemblies are version 9.2.3300, your application uses Crystal Reports 9. If your Crystal Reports managed assemblies are version 10.0.3300, your application uses Crystal Reports 10.
To deploy an application that uses Crystal Reports for Visual Studio .NET 2002
1. Ensure that the assembly version of the Crystal Reports managed components is 9.1.3300. 2. Go to http://support.businessobjects.com/search and download "crnet_deployment.pdf". 3. Open Crnet_deployment.pdf and refer to the 'Crystal Reports Bundled Version with VS 2002' section.
To deploy an application that uses Crystal Reports for Visual Studio .NET 2003
1. Ensure that the assembly version of the Crystal Reports managed components is 9.1.5000. 2. Go to http://support.businessobjects.com/search and download "crnet_deployment.pdf". 3. Open Crnet_deployment.pdf and refer to the 'Crystal Reports Bundled Version with VS 2003' section.
#15 How to deploy an application that uses Crystal Reports and VS .NET
Training:
Learn more about Crystal Reports. Refer to 'Courses & Schedules' at:
http://www.crystaldecisions.com/training
58
#16 What is Unicows.dll and where can you find it? http://support.businessobjects.com/library/kbase/articles/c2011871.asp
Applies to:
Reported version only Unicode runtime Windows 9x/ME
Synopsis
The Crystal Reports (CR) 9 Developer Runtime Help (Runtime.chm) lists Unicows.dll as a dependency file for the Report Designer Component (RDC) and Crystal Print Engine API. What is Unicows.dll and where can you find it?
Solution
NOTE: Windows 9.x and ME are not supported platforms for Crystal Reports (CR) 10 and later. Therefore, Unicows.dll is not supported for the Windows 9.x and ME operating
Unicows.dll is a wrapper to provide Unicode support for Windows 9x and ME (Windows NT, 2000, and XP already provide Unicode support). The Unicows.dll is contained in the RDC 9 merge modules. To download the RDC 9 merge modules, go to http://support.businessobjects.com/search and download Cr9rdcmergemodules.zip. For information on deploying an RDC 9 application, go to http://support.businessobjects.com/search and download rdc9_deployment.pdf. Search for this file at: http://support.businessobjects.com/search
59
#17 How to change the data source using CR for VS .NET application
#17 How to change the data source using CR for VS .NET application http://support.businessobjects.com/library/kbase/articles/c2011464.asp
Applies to:
Reported version only Database connectivity Change Database and Server
Synopsis
An application uses Crystal Reports for Visual Studio .NET as the reporting development tool. How do you change the database and server in a report at runtime? For example, if a report is designed against the 'pubs1' database and the 'server1' server, how can you change the database to 'pubs2' and the server to 'server2'?
Solution
To change the database and server at runtime, copy one of the following code samples into your class (use the logon method defined in the code to change the database and server):
// Helper method that iterates through all tables // in a report document bool ApplyLogon(ReportDocument cr, ConnectionInfo ci) { TableLogOnInfo li;
60
#17 How to change the data source using CR for VS .NET application
CAUTION: When using ODBC, the DSN name is the server name. The DSN should be under the System DSN, and not under the User DSN. The Logon method cannot change database file name when using DAO (Microsoft Access File/.mdb). If you have a subreport that connects to a different database or server than your main report, use the ApplyLogon method instead of the Logon method. When using the ApplyLogon method, ensure you iterate through each subreports. It is not possible to use the CR for VS .NET SDK to change a report from using SQL Authentication to Windows Authentication, or vice versa. This functionality is available through the Report Application Server (RAS) .NET SDK or Report Designer Component (RDC).
// for each table apply connection info foreach (Table tbl in cr.Database.Tables) { li = tbl.LogOnInfo; li.ConnectionInfo = ci; tbl.ApplyLogOnInfo(li); // check if logon was successful // if TestConnectivity returns false, check // logon credentials if (tbl.TestConnectivity()) { // drop fully qualified table location if (tbl.Location.IndexOf(".") > 0) { tbl.Location = tbl.Location.Substring(tbl.Location.LastIndexOf(".") + 1); } else tbl.Location = tbl.Location; } else return(false) } return(true); } // The Logon method iterates through all tables
61
#17 How to change the data source using CR for VS .NET application
bool Logon(ReportDocument cr, string server, string db, string id, string pass) { ConnectionInfo ci = new ConnectionInfo(); SubreportObject subObj; ci.ServerName = server; ci.DatabaseName = db; ci.UserID = id; ci.Password = pass; if (!ApplyLogon(cr, ci)) return (false); foreach (ReportObject obj in cr.ReportDefinition.ReportObjects) { if (obj.Kind == ReportObjectKind.SubreportObject) { subObj = (SubreportObject)obj; if (!ApplyLogon(cr.OpenSubreport(subObj.SubreportName), ci)) return(false); } } return (true); }
---------------------- VB .NET ---------------------
Function ApplyLogon(ByVal cr As ReportDocument, ByVal ci As ConnectionInfo) As Boolean Dim li As TableLogOnInfo Dim tbl As Table ' for each table apply connection info For Each tbl In cr.Database.Tables li = tbl.LogOnInfo li.ConnectionInfo = ci tbl.ApplyLogOnInfo(li) ' check if logon was successful ' if TestConnectivity returns false, ' check logon credentials If (tbl.TestConnectivity()) Then 'drop fully qualified table location If (tbl.Location.IndexOf(".") > 0) Then tbl.Location = tbl.Location.Substring(tbl.Location.LastIndexOf(".") + 1)
62
#17 How to change the data source using CR for VS .NET application
Else tbl.Location = tbl.Location End If Else Return False End If Return True Next End Function 'The Logon method iterates through all tables Function Logon(ByVal cr As ReportDocument, ByVal server As String, ByVal db As String, ByVal id As String, ByVal pass As String) As Boolean Dim ci As New ConnectionInfo() Dim subObj As SubreportObject ci.ServerName = server ci.DatabaseName = db ci.UserID = id ci.Password = pass If Not (ApplyLogon(cr, ci)) Then Return False End If Dim obj As ReportObject For Each obj In cr.ReportDefinition.ReportObjects If (obj.Kind = ReportObjectKind.SubreportObject) Then subObj = CType(obj, SubreportObject) If Not (ApplyLogon(cr.OpenSubreport(subObj.SubreportName), ci)) Then Return False End If End If Next Return True End Function
63
#17 How to change the data source using CR for VS .NET application
64
#18 How to pass Database logon info to a Crystal Report at runtime in VB .NET
#18 How to pass Database logon info to a Crystal Report at runtime in VB .NET http://support.businessobjects.com/library/kbase/articles/c2010371.asp
Applies to:
Reported version only Logon Information TableLogonInfo
Synopsis:
A VB .NET application uses Crystal Reports for Visual Studio .NET as the reporting development tool. How do you pass database logon information to a Crystal Report at runtime in this VB .NET application?
Solution:
To pass logon information to a Crystal Report at runtime, use the following code sample:
<VB .NET> -----------
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Dim crtableLogoninfos As New TableLogOnInfos() Dim crtableLogoninfo As New TableLogOnInfo() Dim crConnectionInfo As New ConnectionInfo() Dim CrTables As Tables Dim CrTable As Table Dim TableCounter 'If you are using a Strongly Typed report (Imported in 'your project) named CrystalReport1.rpt use the 'following: Dim crReportDocument As New CrystalReport1()
65
#18 How to pass Database logon info to a Crystal Report at runtime in VB .NET
'If you are using a Non-Typed report, and loading a report outside of the project, use the 'following: Dim crReportDocument As New ReportDocument() crReportDocument.Load("c:\myReports\myReport.rpt") 'Set the ConnectionInfo properties for logging on to the Database 'If you are using ODBC, this should be the DSN name NOT the physical server name. If 'you are NOT using ODBC, this should be the physical server name With crConnectionInfo .ServerName = "DSN or Server Name" 'If you are connecting to Oracle there is no DatabaseName. Use an empty string. 'For example, .DatabaseName = "" .DatabaseName = "DatabaseName" .UserID = "Your User ID" .Password = "Your Password" End With 'This code works for both user tables and stored procedures. Set the CrTables to the Tables 'collection of the report CrTables = crReportDocument.Database.Tables 'Loop through each table in the report and apply the LogonInfo information For Each CrTable in CrTables CrTableLogonInfo = CrTable.LogonInfo CrTableLogonInfo.ConnectionInfo = crConnectionInfo CrTable.ApplyLogOnInfo(crtableLogoninfo) 'If your DatabaseName is changing at runtime, specify the table location. 'For example, when you are reporting off of a Northwind database on SQL server you 'should have the following line of code: crTable.Location = "Northwind.dbo." & crTable.Location.Substring(crTable.Location.LastIndexOf(".") + 1) Next 'Set the viewer to the report object to be previewed. CrystalReportViewer1.ReportSource = crReportDocument
66
#18 How to pass Database logon info to a Crystal Report at runtime in VB .NET
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; private CrystalReport1 crReportDocument = new CrystalReport1 (); private Database crDatabase; private Tables crTables; private Table crTable; private TableLogOnInfo crTableLogOnInfo; private ConnectionInfo crConnectionInfo = new ConnectionInfo (); //Setup the connection information structure to log on to the data source for the report. // If using ODBC, this should be the DSN. If using OLEDB, etc, this should be the physical //server name crConnectionInfo.ServerName = "DSN or Server Name"; // If you are connecting to Oracle there is no // DatabaseName. Use an empty // string i.e. crConnectionInfo.DatabaseName = ""; crConnectionInfo.DatabaseName = "DatabaseName"; crConnectionInfo.UserID = "Your UserID"; crConnectionInfo.Password = "Your Password"; // This code works for both user tables and stored procedures //Get the table information from the report crDatabase = crReportDocument.Database; crTables = crDatabase.Tables; //Loop through all tables in the report and apply the connection information for each table. for (int i = 0; i < crTables.Count; i++) { crTable = crTables [i]; crTableLogOnInfo = crTable.LogOnInfo; crTableLogOnInfo.ConnectionInfo = crConnectionInfo; crTable.ApplyLogOnInfo(crTableLogOnInfo);
67
#18 How to pass Database logon info to a Crystal Report at runtime in VB .NET
//If your DatabaseName is changing at runtime, specify the table location. For example, when //you are reporting off of a Northwind database on SQL server you should have the following //line of code: crTable.Location = "Northwind.dbo." + crTable.Location.Substring(crTable.Location.LastIndexOf (".") + 1) }
68
#18 How to pass Database logon info to a Crystal Report at runtime in VB .NET
69
#19 How to create a report and add a parameter field using Report Creation API
#19 How to create a report and add a parameter field using Report Creation API http://support.businessobjects.com/library/kbase/articles/c2007184.asp
Applies to:
Reported version and higher Report Creations API Creating a Parameter field at runtime Including the Parameter field in a record selection formual
NOTE: For more articles on using the Report Designer Component's Report Creation API search on the keyword 'RCAPI' at http://support.crys taldecisions.com/k base All Runtime Report Creation functionality requires licensing. For more information, please visit http://www.crystal decisions.com/pro ducts/crystalreport
Synopsis
This article is part of a series of Knowledge Base articles that demonstrate the Report Creation API (RCAPI) available in the Report Designer Component for Crystal Reports Version 8 Developer Edition. This article demonstrates how to: - Create a report at runtime (RCAPI Method: 'NewReport') - Add a table from a Native connection to Microsoft Access. (RCAPI Method: 'Add') - Add a parameter field to the ParameterFieldDefinitions collection. (RCAPI Method: 'Add') - Create a record selection formula that includes the parameter field. - Add database fields to the report. (RCAPI Method: 'AddFieldObject') - Display the report.
Solution
This tutorial assumes that the developer has prior knowledge of Microsoft Visual Basic, Crystal Reports, and the Report Designer Component. The following procedure and sample code creates an application that demonstrates the RCAPI methods outlined in the Synopsis. 1. On the 'Project' menu in Microsoft Visual Basic click 'References'. The 'References' dialog box appears.
70
#19 How to create a report and add a parameter field using Report Creation API
NOTE: For more information on the RCAPI refer to the 'Seagate Crystal Reports 8 Technical Reference Guide'. The guide can be found in the Docs folder of the Crystal Report 8 installation CD.
2. In the dialog box select the 'Crystal Report 8 ActiveX Designer Run Time Library' check box. Click 'OK' to save the changes. 3. On the 'Project' menu, click 'Components'. The 'Components' dialog box appears. 4. In the dialog box click 'Controls', select the 'Crystal Report Viewer' check box and then click 'Apply'. This adds the CRViewer icon to the Microsoft Visual Basic toolbar. Click 'OK' to save the changes. 5. On the Microsoft Visual Basic toolbar double-click 'CRViewer'. The Crystal Report Viewer is added to the form. 6. Double-click 'Form1' to open the 'Code' module. Insert the 'Sample RDCAPI code' in the code module. 7. Once you have inserted the code, on the 'Run' menu, click 'Start' to run the application.
Option Explicit 'RDC Runtime Objects used in this sample. Dim crApplication As CRAXDRT.Application Dim crReport As CRAXDRT.Report '*********************************************** 'The Form_Load event creates an instance of the RDC engine, then makes calls to routines 'that will setup the report and finally display the report in the Crystal Report Viewer control. '*********************************************** Private Sub Form_Load() 'Create an instance of the RDC engine Set crApplication = New CRAXDRT.Application 'Create a new report Set crReport = crApplication.NewReport 'Calling a routine that will add a database connection for the report Call AddDatabase 'Calling a routine that will add objects to the Detail section. Call AddToDetails 'Calling a routine that will add a parameter field to the ParameterFieldDefinitions collection, 'and include the parameter in a record selection formula. Call AddParameterField
71
#19 How to create a report and add a parameter field using Report Creation API
'Set the Report Viewer control to a report to view CRViewer1.ReportSource = crReport 'Display the report in the Crystal Report Viewer CRViewer1.ViewReport End Sub '*********************************************** 'The AddDatabase() routine is used to add a native database connection to the sample 'database, Xtreme.MDB. In this sample the 'Customer' table is being added. '*********************************************** Public Sub AddDatabase() 'Variables used to setup the Database connection Dim crDBTables As CRAXDRT.DatabaseTables Dim sDatabasePath As String Dim sTableName As String 'Get the Tables collection because it has the Add() method needed 'to add a connection to the report Set crDBTables = crReport.Database.Tables 'Set the values for the connection variables The full path and name of the Access database. 'The database resides in the same directory as the application ' sDatabasePath = App.Path & "\xtreme.mdb" 'The name of the Access table sTableName = "Customer" 'Use the .Add() method to add the database table to the report. There are several optional 'arguments for the Add method. Which arguments are passed will depend on the type of 'database, the type of table and the type of connection. 'Add the 'Customer' table crDBTables.Add sDatabasePath, sTableName End Sub '*********************************************** 'The AddToDetails () routine is used to add objects to the Detail section. In this case, two 'fields from the 'Customer' table are added. '*********************************************** Public Sub AddToDetails() Dim crSection As CRAXDRT.Section Dim crFieldObject As CRAXDRT.FieldObject
72
#19 How to create a report and add a parameter field using Report Creation API
'****Add database fields and the formula field to the Details section***** 'Since we are working with the Details section of the report, we need to get the 'D' section of 'the report. Set crSection = crReport.Sections.Item("D") '**Add the 'Customer Name and 'Last Year's Sales' fields to the details section** 'Set a Field object to the AddFieldObject method of the Detail Section 'The Field parameter is set to the table.fieldname 'The Left and Top parameters are passed as integers to position the field Set crFieldObject = crSection.AddFieldObject("{Customer.Customer Name}", 600, 0) Set crFieldObject = crSection.AddFieldObject("{Customer.Last Year's Sales}", 3720, 0) End Sub
'*********************************************** 'The AddParameterField () routine is used to add a parameter field to the 'ParameterFieldDefinitions collection. The default values for the parameter field will be set and 'the parameter will be included in a record selection formula '*********************************************** Public Sub AddParameterField() Dim crParameterFields As CRAXDRT.ParameterFieldDefinitions 'Since we are adding a formula field to the ParameterFieldDefinitions collection we need to get 'the ParameterFields from the report object Set crParameterFields = crReport.ParameterFields 'Add a parameter field to the ParameterFieldDefinitions Collection The ParameterName 'parameter is set to the name of the new parameter The ValueType parameter specifies the 'value type to be passed to the parameter crParameterFields.Add "Sales Maximum Value", 'crCurrencyField
73
#19 How to create a report and add a parameter field using Report Creation API
'With the new parameter field set the default values Set the Value to be a single discrete 'value and do not allow multiple values This is the first parameter field created in the report so 'we access the first item in the ParameterFieldDefinitions collection With crReport.ParameterFields(1) .AddDefaultValue 50 .AddDefaultValue 500 .AddDefaultValue 10000 .AddDefaultValue 25000 .AddDefaultValue 50000 .AddDefaultValue 100000 .AddDefaultValue 150000 .AddDefaultValue 200000 .AddDefaultValue 250000 .AddDefaultValue 500000 .AddDefaultValue 1000000 .DiscreteOrRangeKind = crDiscreteValue .EnableMultipleValues = False End With 'Pass a record selection formula to the report The record selection formula contains the newly 'created parameter When the report is run the parameter will prompt the user. The default 'values set previously will be available to the user to select the name of the parameter field in 'the recordslection formula will follow this format: '{? + The name of the new parameterfield + } 'crReport.RecordSelectionFormula = "{Customer.Last Year's Sales} < {?Sales Maximum 'Value}" End Sub '*********************************************** 'The Form_Resize event is used to size the Crystal Report 'Viewer control to the size of the Parent form (Form1). '*********************************************** Private Sub Form_Resize() With CRViewer1 .Top = 0 .Left = 0 .Width = Me.ScaleWidth .Height = Me.ScaleHeight End With End Sub '*********************************************** 'The Form_Unload event is used to clean up the objects
74
#19 How to create a report and add a parameter field using Report Creation API
'used by the sample application. '*********************************************** Private Sub Form_Unload(Cancel As Integer) 'Destroy the Report object Set crReport = Nothing 'Destroy the Application object Set crApplication = Nothing End Sub
75
Applies to:
Reported version only Documentation
Synopsis
Where can you find documentation or help files for Crystal Reports for Visual Studio .NET (VS .NET)?
Solution
Crystal Reports documentation is included as part of the VS .NET documentation. Documentation is available online at the Microsoft Developer Network (MSDN) web site and is also bundled with VS .NET as part of MSDN. The following link leads directly to the Crystal Reports for VS .NET documentation in the MSDN Library: MSDN Website: http://msdn.microsoft.com/library/?url=/library/enus/crystlmn/html/crconcrystalreports.asp?frame=true
Microsoft Visual Studio .NET
You can also find CR for VS .NET resources on the Business Objects support site.
Documentation is accessible through a variety of methods in VS .NET. The common ones are:
Searching for "Crystal Reports" in the VS .NET documentation index. ontext sensitive help: Click the insertion point on a Crystal property method or object in the VS .NET code editor, and press the F1 key. A tab appears in the VS.NET IDE with documentation on what code is covered by the insertion point http://www.businessobjects.com/services/training/crystalreports.asp
76
Business Objects Support Site Download .NET documentation at http://support.businessobjects.com/library/docfiles/cps10/docs_en.asp Download VS .NET sample applications at http://support.businessobjects.com/fix/samplescr.asp Download VS .NET white papers by searching for "crnet*" at http://support.businessobjects.com/search
77
Summary
Summary:
Whether you are a novice or an expert, there are additional resources available to help you get more from your investment. To investigate all of the options, please visit http://www.businessobjects.com/services/training/crystalreports.asp You might also want to consider certification. 73% of employees surveyed said certification played a significant role in career advancement. (Certification Magazines 2003 Salary Survey, December 2003.) http://www.businessobjects.com/services/training/crystal/certification.asp A final tip: If you are responsible for team or organization training or if user adoption is important to you, we have a white paper just for you. The comprehensive report is free of charge download your copy by visiting www.businessobjects.com/training Thank you for investing the time to learn our Crystal Reports secrets. We hope that you already feel more confident in your ability to design better reports, faster. If you have any questions, please contact us. Our customer service representatives are ready to help you. In North America call 1-866-665-4176 or contact a worldwide office.
78
Americas Business Objects Americas 3030 Orchard Parkway San Jose, California 95134 USA Tel: +1 408 953 6000 +1 800 877 2340 Asia-Pacific Business Objects Asia Pacific Pte Ltd 350 Orchard Road #20-04/06 Shaw House 238868 Singapore Tel: +65 6887 4228 Europe, Middle East, Africa Business Objects, SA 157-159 rue Anatole France 92309 Levallois-Perret Cedex France Tel: +33 1 41 25 21 21 Japan Business Objects Japan K.K. Head Office Yebisu Garden Place Tower 28th Floor 4-20-3 Ebisu, Shibuya-ku Tokyo 150-6028 Tel: +81 3 5720 3570 For a complete listing of our sales offices, please visit our website. http://www.businessobjects.com
79