You are on page 1of 29

Writing Reports with the Microsoft Data

Report Designer

The Microsoft Data Report designer is a versatile data report generator that features the
ability to created banded hierarchical reports. Used in conjunction with a data source such
as the Data Environment designer, you can create reports from several different relational
tables. In addition to creating printable reports, you can also export the report to HTML
or text files.

Possible Uses
• Automatically create reports that are exported in HTML format for instant
distribution on the Internet.

• Create reports that show the sums of transactions occurring on a daily basis.

Data Report Designer Features


The Data Report designer has several features:
1. Drag-and-Drop Functionality for Fields—Drag fields from the Microsoft Data
Environment designer to the Data Report designer. When you do this, Visual
Basic automatically creates a text box control on the data report and sets the
DataMember and DataField properties of the dropped field. You can also drag a
Command object from the Data Environment designer to the Data Report
designer. In that case, for each of the fields contained by the Command object, a
text box control will be created on the data report; the DataMember and DataField
property for each text box will be set to the appropriate values.

2. Toolbox Controls—The Data Report designer features its own set of controls.
When a Data Report designer is added to a project, the controls are automatically
created on a new Toolbox tab named DataReport. Most of the controls are
functionally identical to Visual Basic intrinsic controls, and include a Label,
Shape, Image, TextBox, and Line control. The sixth control, the Function control,
automatically generates one of four kinds of information: Sum, Average,
Minimum, or Maximum. For more information about the Function control, see
"Adding a Function Control to the Data Report."

3. Print Preview—Preview the report by using the Show method. The data report is
then generated and displayed in its own window.
Note A printer must be installed on the computer to show the report in print
preview mode.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


4. Print Reports—Print a report programmatically by calling the PrintReport
method. When the data report is in preview mode, users can also print by clicking
the printer icon on the toolbar.
Note A printer must be installed on the computer to print a report.
5. File Export—Export the data report information using the ExportReport method.
Formats for export include HTML and text.

6. Export Templates—You can create a collection of file templates to be used with


the ExportReport method. This is useful for exporting reports in a variety of
formats, each tailored to the report type.

7. Asynchonous Operation—The DataReport object's PrintReport and


ExportReport methods are asynchronous operations. Using the
ProcessingTimeout event, you can monitor the state of these operations and
cancel any that are taking too long.

Topics
• Parts of the Data Report

• Creating a Simple Data Report

• Exporting a Data Report

• Printing a Data Report

• Data Report Events

• Understanding Control Placement on the Data Report Designer

Sample Application
The sample application named prjNwind corresponds to the project built in the series of
topics that begin with "Creating a Simple Data Report." If you have installed the Visual
Basic sample applications, the file can be found in the Samples directory. If you have not
installed the sample applications, the file can be found on the MSDN™ CD that
accompanies Visual Basic.

Parts of the Data Report

The Data Report designer consists of the following objects:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


1. DataReport object—Similar to a Visual Basic form, the DataReport object has
both a visual designer and a code module. Use the designer to create the layout of
a report. You can also add code to the designer's code module to
programmatically format controls or sections contained by the designer.

2. Section object—Each section of the Data Report designer is represented by a


Section object in a Sections collection. At design time, each section is represented
by a header that you can click to select the section, and the section's pane where
you can place and position controls. Use the object and its properties to
dynamically reconfigure a report before it is built.

3. Data Report Controls—Special controls that only work on the Data Report
designer are included with it. (Note: you cannot use Visual Basic's intrinsic
controls, or any ActiveX controls, on the Data Report designer). These controls
are found in the Visual Basic Toolbox, but they are placed on a separate tab
named "DataReport."

Sections of the Data Report Designer


The default Data Report designer contains these Sections:
• Report Header—contains the text that appears at the very beginning of a report,
such as the report title, author, or database name. If you want the Report Header
to be the first page in the report, set its ForcePageBreak property to
rptPageBreakAfter.

• Page Header—contains information that goes at the top of every page, such as the
report's title.

• Group Header/Footer—contains a "repeating" section of the data report. Each


group header is matched with a group footer. The header and footer pair are
associated with a single Command object in the Data Environment designer.

• Details—contains the innermost "repeating" part (the records) of the report. The
details section is associated with the lowest-level Command object in a Data
Environment hierarchy.

• Page Footer—contains the information that goes at the bottom of every page, such
as the page number.

• Report Footer—contains the text that appears at the very end of the report, such as
summary information, or an address or contact name. The Report Footer appears
between the last Page Header and Page Footer.

Data Report Controls

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


When a new Data Report designer is added to a project, the following controls are
automatically placed in the Toolbox tab named DataReport:
• TextBox Control (RptTextBox)—allows you to format text, or assign a
DataFormat.

• Label Control (RptLabel)—allows you to place labels on the report to identify


fields or sections.

• Image Control (RptImage)—enables you to place graphics on your report. Note


that this control cannot be bound to a data field.

• Line Control (RptLine)—lets you draw rules on the report to further distinguish
sections.

• Shape Control (RptShape)—enables you to place rectangles, triangles, or circles


(and ovals) on a report.

• Function Control (RptFunction)—a special text box that calculates values as the
report is generated.

Creating a Simple Data Report

This topic creates a simple data report using a Data Environment designer as a data
source. The Data Environment designer uses the NorthWind database supplied with
Visual Basic to create a simple hierarchical cursor. The cursor contains two tables,
Customers and Orders, and uses the CustomerID field to link the two. The finished report
resembles the figure below.
Simple Data Report: Order Dates by Customers

Before you begin the step-by-step process, ensure that the Northwind database
(Nwind.mdb) is present on your computer. If it is not present, copy the file from your
Visual Basic CD onto your hard disk.

To create a simple hierarchical cursor in the Data Environment designer


1. Create a new Standard EXE project.

2. On the Project menu, click Add Data Environment to add a designer to your
project. If the designer is not listed on the Project menu, click Components.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Click the Designers tab, and click Data Environment to add the designer to the
menu.
Note The first four kinds of ActiveX designers loaded for a project are listed on
the Project menu. If more than four designers are loaded, the later ones will be
available from the More ActiveX Designers submenu on the Project menu.
3. On the Data Link Properties dialog box, click Microsoft Jet 3.51 OLE DB
Provider. This selects the correct OLE DB provider for accessing a Jet database.

4. Click the Next button to get to the Connection tab.

5. Click the ellipsis button (…) next to the first text box.

6. Use the Select Access Database dialog box to navigate to the nwind.mdb file,
which is installed in the Program Files\Microsoft Visual Studio\Vb98 directory.

7. Click OK to close the dialog box.

8. Right-click the Connection1 icon, and click Rename. Change the name of the
icon to Northwind.

9. Right-click the Northwind icon, and then click Add Command to display the
Command1 dialog box. In the dialog box, set the properties as shown below:
Property Setting
Command Name Customers
Connection Northwind
DataBase Object Table
Object Name Customers
10.
11. Click OK to close the dialog box.

12. Right-click the Customers command, and click Add Child Command to display
the Command2 dialog box. In the dialog box, set the properties as shown below:
Property Setting
Command Name Orders
Connection Northwind
DataBase Object Table
Object Name Orders
13.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


14. Click the Relation tab. The Relate to a Parent Command Object check box
should be checked. The Parent box should contain Customers; both the Parent
Fields and Child Fields/Parameters boxes should contain CustomerID.
When designing relational databases, it's customary for related tables to use the
same name for linking fields. In this case, the linking fields are both named
CustomerID. The Data Environment designer automatically matches such pairs in
the dialog box.
15. Click Add. Click OK to close the dialog box.
Clicking the Add button adds the relation to the Command object. After closing
the dialog box, the Data Environment designer reflects the relationship by
displaying the two commands as a hierarchy. This hierarchy will be used to create
the data report.
16. Set the properties of the project and designer according to the settings below, then
save the project:
Object Property Setting
Project Name prjNwind
DataEnvironment Name deNwind
Form Name frmShowReport
17.

Creating the Data Report


Once the Data Environment designer has been created, you can create a data report.
Because not all of the fields in the data environment will be useful in a report, this series
of topics creates a limited report that displays only a few fields.

To create a new data report


1. On the Project menu, click Add Data Report, and Visual Basic will add it to
your project. If the designer is not on the Project menu, click Components. Click
the Designers tab, and click Data Report to add the designer to the menu.
Note The first four kinds of ActiveX designers loaded for a project are listed on
the Project menu. If more than four designers are loaded, the later ones will be
available from the More ActiveX Designers submenu on the Project menu.
2. Set the properties of the DataReport object according to the table below:
Property Setting
Name rptNwind
Caption Northwind Data Report

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


3. On the Properties window, click DataSource and then click deNwind. Then
click DataMember and click Customers.
Important To set the DataSource property to deNwind, the Data Environment
designer must be open. If it is closed, press CTRL+R to display the Project
window, then double-click the data environment icon.
4. Right-click the Data Report designer, and click Retrieve Structure.
You have added a new group section to the designer. Each group section has a
one-to-one correspondence to a Command object in the data environment; in this
case, the new Group section corresponds to the Customers Command object.
Notice also that the Group Header has a matching Group Footer section.
Note The Data Environment allows you to create hierarchies of Command
objects wherein a Command object has more than one child object — child
Command objects parallel to each other. The Data Report designer, however, is
not as flexible, and can't display more than one child object at a time. In such
cases, when executing a Retrieve Structure command, the Data Report will
display only the first of the child commands, and none below it. Thus you should
avoid creating Command hierarchies with parallel children commands.
5. From the Data Environment designer, drag the CompanyName field (under the
Customers command) onto the Group Header (Customers_Header) section.
The Group Header section can contain any field from the Customers command,
however, for demonstration purposes, only the Customer name is displayed at this
time.
6. Delete the Label control (rptLabel) named Label1.
If you do not want a Label control to be included with the TextBox control, you
can uncheck the Drag and Drop Fields Caption option on the Field Mapping
tab of the Data Environment designer's Options dialog box.
7. From the Data Environment designer, drag the OrderDate field (under the
Orders command) onto the Details (Orders_Detail) section. Delete the Label
control.

The Details section represents the innermost "repeating" section, and thus
corresponds to the lowest Command object in the Data Environment hierarchy:
the Orders Command object.

8. Resize the Data Report designer's sections to resemble the figure below:

It's important to resize the height of the Details section to be as short as possible
because the height will be multiplied for every OrderDate returned for the

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


CompanyName. Any extra space below or above the OrderDate text box will
result in unneeded space in the final report.
9. Save the project.

Preview the Data Report Using the Show Method


Now that the data environment and the data report objects have been created, you are
almost ready to run the project. One step remains: to write code to show the data report.

To show the data report at run time


1. On the Project Explorer window, double-click the frmShowReport icon to
display the Form designer.

2. On Toolbox, click the General tab.


When you add a Data Report designer to your project, its controls are added to the
tab named DataReport. To use the standard Visual Basic controls, you must
switch to the General tab.
3. Click the CommandButton icon and draw a CommandButton on the form.

4. Set the properties of the Command1 control according to the table below:
Property Setting
Name cmdShow
Caption Show Report
5.
6. In the button's Click event, paste the code below.
7. Private Sub cmdShow_Click()
8. rptNwind.Show
End Sub
9. Save and run the project.

10. Click Show Report to display the report in print preview mode.

Optional—Setting the Data Report as the Startup Object


You can also display the data report with no code at all.
1. On the Project menu, click prjNwind Properties.

2. In the Startup Object box, select rptNwind.

3. Save and run the project.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Note If you use this method, you can remove the Form object from your project.

Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
Go to the next step Extending the Data Report

Exporting a Data Report

After compiling a report you may wish to reuse it, either as part of a larger document or
perhaps for distribution on an intranet or the Internet. The Data Report designer's
ExportReport method allows you to accomplish these tasks. Using the ExportReport
method, you can export any report as a text file or as an HTML file. Additionally, you
can use any of a number of ExportFormat objects to tailor the content and appearance of
an exported file.

Important The ExportReport method does not support the exporting of images or
graphic shapes.

ExportFormat Objects
The ExportReport method was designed to work with the ExportFormats collection. Each
ExportFormat object in the collection represents a separate format for the report. For
example, a report formatted for intranet distribution might include names of groups or
employees as part of the report header; for Internet distribution, those same names would
be removed or replaced. You would therefore create at least two ExportFormat objects,
each tailored for the distribution mechanism. However, it is possible to export a report
without creating any ExportFormat objects because four are already provided for you.

Four Default ExportFormat Objects


By default, the ExportFormats collection contains four members. The four members and
their associated file filters are shown in the chart below:
Object File Filter Description
ExportFormats(1) *.htm, *.html HTML
ExportFormats(2) *.htm, *.html Unicode HTML
ExportFormats(3) *.txt Text
ExportFormats(4) *.txt Unicode Text

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


If you need to use any of the default types, you can also use the Key property to specify a
default type. The Key property values and the constants are shown below:
Object Key Constant
ExportFormats(1) key_def_HTML rptKeyHTML
ExportFormats(2) key_def_UnicodeHTML_UTF8 rptKeyUnicodeHTML_UTF8
ExportFormats(3) key_def_Text rptKeyText
ExportFormats(4) key_def_UnicodeText rptKeyUnicodeText

By using one of the four members, you can export a report without creating another
ExportFormat object, provided the default meets your requirements. For example, to
export a daily HTML report, you might use the following code:
DataReport1.ExportReport rptKeyHTML

Displaying a Dialog Box Is Optional


The programmer can determine whether or not a dialog box will be presented when
exporting a report. For example, if the report is created automatically every morning, and
written to the same file for distribution by an intranet, there is no need to display a dialog
box. As long as a valid file path and key are supplied, and the Overwrite parameter is set
to True, the dialog will not be displayed.
' Export a report as HTML, overwriting any existing file. Export
' all pages to the Daily_Report.htm file.
DataReport1.ExportReport rptKeyHTML, "C:\Temp\Daily_Report", True, , _
rptRangeAllPages
Note In the above code the second argument seems to be a directory but is actually the
file name. "Daily_Report.htm" is the name of the written file. The ExportFormat object
supplies the file extension (.htm), and thus there's no need to write it in the file name
argument.

ExportFormat Supplies Dialog Information


The ExportFormat object also contains the information that is displayed when the user
invokes the ExportReport method. In particular, the FileFormatString property sets the
text that is displayed in the Export dialog box's Save As Type box. For example, imagine
that a company has a standard ExportFormat object to be used with all reports. The
following code would ensure that the ExportFormat is available from the list of format
types on the Export dialog box:
Dim strTemplate As String

' First create the template for the ExportFormat object.


strTemplate = "MyCompany Daily Report" & vbCrLf & rptTagBody

' Add an ExportFormat object. The FileFormatString determines


' what will be displayed in the Export dialog box.
DataReport1.ExportFormats.Add _
Key:="StandardReport", _
FormatType:=rptFmtText, _

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


FileFormatString:="Standard Report (*.txt)", _
FileFilter:="*.txt", _
Template:=strTemplate

' Invoke the ExportReport method specifying the ExportFormat


' object named StandardReport to use.
DataReport1.ExportReport "StandardReport", , False, True, _
rptRangeFromTo, 1, 10
When invoked, the Export dialog box resembles this:

Template Codes
The core of an ExportFormat object is its template. A template is simply a string
containing both the text you want to appear along with constants that represent various
parts of the data report. The constants, values, and descriptions are shown in the table
below:
Constant Value Description
rptTagTitle <!--MSDBRPT_Template_Title--> Represents the title of the
report, as found in the Title
property.
rptTagBody <!--MSDBRPT_Template_Body--> Represents the body of the
report.

To create a simple data report that includes only the name of the author followed by the
body of the report, the template would resemble this:
Dim strT As String
strT = "Author: " & InputBox("Your name") & vbCrLf & rptTagBody
drpNwind.ExportFormats.Add "AuExp", rptFmtText, _
"Author Only Text File", "*.txt", strT

Printing a Data Report

Printing a data report can be accomplished in one of two ways. The user can click the
Print button that appears on the data report in Print Preview mode (using the Show
method), or you can programmatically enable printing using the PrintReport method. If
an error occurs during printing, trap it in the Error event.
For More Information See "Data Report Events."

Choosing to Display a Print Dialog Box


When printing a report programmatically, you have two choices: to print by displaying
the Print dialog box, or by printing without displaying the dialog box.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


To display the Print dialog box
1. Add a CommandButton to a Form.

2. In the button's Click event, place the following code:


3. DataReport1.PrintReport True
The Print dialog box allows the user to select a printer, print to file, select a range of
pages to print, and specify the number of copies to print.
Note Printers must be installed on the computer in order to present a choice of printers.

Printing Without a Dialog Box


In some cases, you may wish to print the report without user intervention. The
PrintReport method also gives you the option of selecting a range of pages to print, either
all, or a specified range.

To print without displaying the dialog box


1. Add a CommandButton to a Form.

2. In the button's Click event, place the following code:


3. DataReport1.PrintReport False
Or, to specify a range of pages to print, use the code below:
DataReport1.PrintReport False, rptRangeFromTo, 1, 2

Visual Basic Concepts

Data Report Events

Like the standard Visual Basic form, the life of a Data Report designer is marked by
certain key events. Those events, and the order in which they occur, are shown in the
following table:
Event Description
Initialize Occurs after the query has completed, and controls are sited on the
form.
Resize Occurs when the designer is first displayed or when the window
state of an object changes.
Activate Occurs when the designer becomes the active window.
ProcessingTimeout Occurs approximately once every second until all processing has
ended. Use this event to determine if processing has taken too long,
and to cancel the processing.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Note This event will not occur until the query has completed. See
below.
[Deactivate] Occurs when the designer is no longer the active window. Use this
event to determine if the user has clicked another form or designer.
QueryClose Occurs before the designer is terminated. Set the Cancel argument
to True to cancel termination. The CloseMode argument returns the
type of action that is causing the termination.
Terminate Occurs when all references to the designer have been set to 0.

Timeout and Asynchronous Call Events


In addition to the designer's lifetime events, the DataReport object also features events
that allow you to trap errors and monitor synchronous and asynchronous function calls.

ExportReport and PrintReport: Query, Synchronous and Asynchronous


Processes
When either the ExportReport or PrintReport method is invoked, the process is divided
into three stages—the query, synchronous processing, and asynchronous printing or
exportation:

1. Query—When the data report is first created, a query is sent to the data provider.

2. Processing—The data retrieved by the query is processed by Visual Basic to


create the report. The data is cached in a temporary file on the computer. This
process is synchronous.

3. Asynchronous Printing or Exporting—After creating the report, the report is


exported or printed. This process is asynchronous.
When the Show method is invoked, the data report executes the query and then processes
the data in a synchronous process before displaying the report.

Because these methods combine both synchronous and asynchronous processes, there are
separate events to monitor each kind of process.

The ProcessTimeOut Event—for Synchronous Functions


Processing a large data report may take some time. If you want to allow your users to
cancel out of a lengthy operation (such as Show, ExportReport, or PrintReport), you can
use the ProcessingTimeout event to monitor how many seconds have passed, and set the
cancel argument to True at the user's command. The code below shows an example.
Private Sub DataReport_ProcessingTimeout(ByVal Seconds As Long, _
Cancel As Boolean, ByVal JobType As MSDataReportLib.AsyncTypeConstants,
_
ByVal Cookie As Long)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Select Case Seconds
Case 30
If MsgBox("This has taken " & Seconds & "seconds. Cancel?", _
vbRetryCancel) = vbCancel Then
Cancel = True
End If
Case 45
If MsgBox("This has taken " & Seconds & "seconds. Cancel?", _
vbRetryCancel) = vbCancel Then
Cancel = True
End If
Case 60
'Cancel automatically after 60 seconds.
Cancel = True
End Select
End Sub
Note It is not guaranteed that the ProcessingTimeout event will occur at the intervals
specified above. For example, other Visual Basic code running in the background may
prevent the event from occurring. In that case, set the Case statement to a range of values;
when the event occurs, set a module-level flag to True, and check it on subsequent
occurrences.

Error Event—For Asynchronous Functions


To trap errors that occur when no Visual Basic code is executing (that is, an
asynchronous function), use the Error event. For example, if the PrintReport or
ExportReport method fails in the asynchronous stage, the Error event will occur. The
example below traps asynchronous errors:
Private Sub DataReport_Error(ByVal JobType As _
MSDataReportLib.AsyncTypeConstants, ByVal Cookie As Long, _
ByVal ErrObj As MSDataReportLib.RptError, ShowError As Boolean)
Select Case JobType ' The JobType identifies the process.
Case rptAsyncPrint
' Trap PrintReport errors here.
Case rptAsyncReport
' Trap ExportReport errors here.
End Select
End Sub
You can also use the Error event to trap specific cases, such as the lack of a printer on the
computer, as shown in the code below:
Private Sub DataReport_Error(ByVal JobType As _
MSDataReportLib.AsyncTypeConstants, ByVal Cookie As Long, _
ByVal ErrObj As MSDataReportLib.RptError, ShowError As Boolean)
Select Case ErrObj.ErrorNumber
Case rptErrPrinterInfo ' 8555
MsgBox "A printing error has occurred. " & _
"You may not have a Printer installed."
ShowError = False
Exit Sub
Case Else
' handle other cases here.
ShowError = True

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


End Select
End Sub

The AsyncProgress Event


The AsyncProgress event is not designed to trap errors, but to allow you to monitor the
state of the asynchronous function. By the time this event occurs, all of the data has been
processed; thus two of the event's arguments are PagesCompleted and TotalPages. The
event also includes arguments that identify the asynchronous operation: the JobType and
Cookie arguments can then be used to monitor the progress of any process.

Understanding Control Placement on the


Data Report Designer

Note You will understand this topic better if you read the Data Report tutorial first,
beginning at Creating a Simple Data Report.
One way of creating a data report is to:
1. Create a Data Environment designer containing a hierarchy of Command objects.

2. Set the DataSource property of the Data Report designer to the Data
Environment designer.

3. Set the DataMember property to the topmost Command object.

4. Right-click the Data Report designer and click Retrieve Structure.

After retrieving the structure, an appropriate number of Group headers and footers
will be created, and each header/footer pair is assigned a name that corresponds to
a Command object.

5. Drag Command objects from the Data Environment designer to the corresponding
section on the Data Report designer.
All of the data fields contained by a Command object are automatically created on
the data report as TextBox controls on the section where the Command object is
dropped. The DataMember and DataField properties of each TextBox are set in
accordance with the Command object and its data fields.
6. Drag TextBox controls from the section where each was created onto a different
section of the Data Report designer.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


7. Add Function controls as needed to the report.

When the data report is bound to a data environment, the rules for placement of controls
on the report are not immediately apparent. This topic explains how the hierarchy created
in the data environment relates to the system of group headers and footers constructed in
the data report.

Command Object Corresponds to Group Header/Footer or Details Section


With two exceptions, every Command object in the data environment corresponds either
to a pair of group header and footer sections, or to the Detail section. The exceptions are
discussed later in this topic.

Hierarchy Versus Headers, Footers, and Detail


The figure below shows a schematic view of the Data Environment designer with four
Command objects, each in a parent/child relationship with at least one other command.
The data fields that belong to the table are not shown.

The Data Report designer, on the other hand, is constructed as a series of sections. And
each section can be categorized into one of four types: Report header/footers, Page
header/footers, Group header/footers, and the Detail section. For the purposes of
instruction, we can disregard the Report and Page header/footer pairs. This leaves the
Group headers/footers and the Detail section.
The Detail section, the innermost section of the designer, corresponds to the lowest-level
Command object. As you go up through the hierarchy, the Detail section is bracketed by
pairs of sections, with each pair associated with a single Command object. The figure
below correlates the Command objects with the sections:
Sections Corresponding to Command Objects

Thus the figure shows that the hierarchy of the data environment actually corresponds to
an expanding series of brackets, with the innermost (Detail) section corresponding to the
lowest level of the hierarchy, and the outermost corresponding to the highest-level
Command object.

Controls Can Be Placed in Any Section in a Lower Level


The placement of a control is governed by what section (or pair of sections) it belongs to.
In brief, a control can be placed in the section where it originates, and in all sections that
are at a level lower than itself. For example, if a control belongs to the Command1
section pair, it can also be placed in the section pairs for Commands 2, 3, and 4. A second
example: A control that originates in section 3 can also be placed in section 4, but not in

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


sections 1 and 2. Taken to its conclusion, controls that originate in the Command 4
section (the Details section) cannot be placed anywhere else except in the Details section.

Placing the Function Control


The Function control has three exceptions to the above guidelines regarding control
placement. The Function control is not directly bound to the recordset, as is the TextBox
control. Instead, the Function control calculates its value as the report is generated. For
this reason, a Function control can only be placed in Footer sections of the report.

A second exception for the Function control: it can only be placed in any section pair that
is one level above its own. For example, if the Command 3 object contains a Quantity
field, you can place a Function control that sums the Quantity values onto the footer
section for Command 2, or the footer section for Command 1.
The third exception concerning the Function control is this: unlike the other data-bound
control (the TextBox control), the Function control can be placed in the Report Footer
section. When you do so, the scope of the control's calculation will be increased to
include the whole report. For example, a Function control placed in the Report footer to
calculate the sum of the Quantity field will calculate the sum of every Quantity control on
the report.

The Exceptions: Grouping and Grand Total Aggregate


With two exceptions, every Command object in the Data Environment corresponds to a
pair of group headers and footers. The first exception occurs when you use the Grouping
feature of the Data Environment designer.

Grouping Fields
When you create grouping fields, the Data Environment designer creates two folders
under a single Command object. The first contains the grouping fields, and the second
contains the Detail fields. Even though a new Command object is not created for the
grouping fields, you must create a new group header/footer pair on the data report and
this requirement qualifies it as an exception.

Grand Total Aggregate Fields


The second exception occurs when you create a Grand Total aggregate field in the data
environment. As happens when creating a grouping field, a new folder is created for the
Command object. The new folder contains any Grand Total aggregate fields created, and
you must add a new group header/footer pair to the data report.

For More Information Details about creating aggregate field can be found in "Creating
Aggregates" in "Using the Data Environment Designer."

Checking the Hierarchy

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


If you are in doubt as to the hierarchy of the Data Environment Command objects, you
have two ways of ensuring that the data report has the correct group header/footer
structure:
Retrieve Structure—If you have not placed many controls onto the Data Report
designer, and you can tolerate the restructuring of your data report, use the Retrieve
Structure command to automatically create the right number of group headers and
footers.
ADO Hierarchy Information—Right-click the topmost Command object in the Data
Environment designer and click Hierarchy Info to display the Hierarchy Information
dialog box. Click the View ADO Hierarchy tab to see a graphical representation of the
Command objects' hierarchy.

Visual Basic Concepts

Extending the Data Report

Once you have a simple data report, it's easy to extend it and make a more complex
presentation. In the procedure below, the data environment is first extended with the
Order Details and Products tables. The extended report includes the names of products
ordered on a specific date, and resembles the figure below.

Extended Data Report With Order Details

Note This topic is part of a series that walks you through creating a sample data report.
It begins with the topic, Creating a Simple Data Report.

To extend the data environment


1. On the Data Environment designer, right-click the Orders Command object.
Then click Add Child Command.

2. On the Command1 Properties dialog box, set the following properties:


Property Setting
Command Name OrderDetails
Connection Northwind
DataBase Object Table
Object Name Order Details
3.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


4. Click the Relation tab. The Relate to a Parent Command Object check box
should be checked. The Parent box should contain Orders; both the Parent
Fields and Child Fields/Parameters boxes should contain OrderID. Click the
Add button and then click OK to close the dialog box.

5. Right-click the OrderDetails Command object, and click Add Child Command.
Set the properties of the connection as shown below:
Property Setting
Command Name Products
Connection Northwind
DataBase Object Table
Object Name Products
6. Click the Relation tab. The Relate to a Parent Command Object check box
should be checked. The Parent box should contain OrderDetails; both the
Parent Fields and Child Fields/Parameters boxes should contain ProductID.
Click the Add button and then click OK to close the dialog box.

Extending the Data Report


Once the data environment has been extended with new tables, you can extend the data
report as well by dragging fields from the Data Environment designer to the Data Report
designer.
To Extend the data report
1. Right-click the Data Report designer, and clear Show Page Header/Footer box.
Clearing this option deletes the page header and footer, which are not being used
at this point.
2. Right-click the Data Report designer, and click Insert Group Header/Footer.
The Insert New Group Header/Footer dialog box will be displayed.

The dialog box allows you to determine if the new header and footer will
"bracket" other header/footer pairs. This becomes important as you add more
header and footer pairs because the outermost pair of header/footers subordinates
all other pairs. This is discussed in greater detail in "Parts of the Data Report."
3. Click OK to select the default placement of the new header and footer pair and
close the dialog box.

4. Select the new group header, and on the Properties window, change its name
from Section1 to Orders_Header. Change the corresponding footer name from
Section4 to Orders_Footer.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


5. Repeat steps 2 to 3. Name the new group header OrderDetails_Header, and the
new group footer OrderDetails_Footer.

6. Click the Detail (Orders_Detail) section to select it. On the Properties window,
change the section's name to Products_Detail.

7. Using the mouse, drag the OrderDate field from the Detail (Products_Detail)
section to the Orders_Header section.

8. From the Data Environment designer, drag the ProductName field (under the
Products command) into the Detail (Products_Detail) section.

9. Delete the Label control named Label1.

10. Resize the group headers, and rearrange the text box controls to resemble the
figure below.

The figure above requires some explanation. First, the Group footers are all closed
in order to take up the least possible space. Like the Details section, any
additional space left in any header or footer will be multiplied in the final report.
Therefore, if a header or footer doesn't contain any fields, you can close the
distance between the headers or footers.
The Group Header named OrderDetails_Header is also closed. If you wonder
why no fields are being shown, you must understand that the Order Details table
in the Northwind database is a join table—the table contains only the IDs of
records from the Orders table joined to IDs of records from the Products table.
Thus the Order Details table doesn't contain fields which are actually displayed.
Instead, it functions only to join two other tables. In the Data Report designer, the
Order Details table therefore functions only to create groups of records—the
product names grouped under the order dates.
Finally, the Details section contains only the names of products. The Details
section contains the innermost level of repeating records.

11. Save and run the project.

Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
Go to the next step Adding a Calculated Field to the Data Report
Start from the beginning Creating a Simple Data Report

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Adding a Calculated Field to the Data
Report

A calculated field is a field whose value is calculated as the report is generated. For
example, when estimating the tax on an order, you must multiply the total price by the
local tax rate. But since local tax rates differ and won't be stored in the database, the tax
is generated as the report is created—a calculated field.

In this example, the extended Data Report designer is modified to include a Total field
that calculates the value of Quantity * UnitPrice. Adding a calculated field involves
the following steps:
1. Using a SQL statement in the data environment's Command object to create the
calculated field.

2. Adding three text box controls to the data report: Quantity, UnitPrice, and (for
the calculated field) Total.
The modified data report resembles the figure below.

Note This topic is part of a series that walks you through creating a sample data report.
It begins with the topic, Creating a Simple Data Report.

To add a calculated field to the data report


1. In the Data Environment designer, right-click the OrderDetails command. Then
click Properties to display the OrderDetails Properties dialog box.

2. On the General tab, click the SQL Statement button, and add the following
statement to the box:
3. Select OrderID, ProductID, UnitPrice, Quantity, (Quantity *
UnitPrice) As Total From [Order Details]
The SQL statement multiplies the Quantity value by the UnitPrice value to create
the Total value—the calculated field. Also note that the name of the table (Order
Details) contains a space, and must be enclosed by brackets.

4. Click OK to close the dialog box.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


5. From the Data Environment designer, drag the Quantity, UnitPrice, and Total
fields (under the OrderDetails command) onto the Detail (Products_Detail)
section of the Data Report designer.

6. Delete two Label controls, and change the Caption value of the remaining Label
control to *, and arrange the controls to resemble the figure below:

7. On the Data Report designer, click the UnitPrice text box to select it. On the
Properties window, double-click DataFormat to display the Property Pages
dialog box.

8. In the Format Type box, click Currency. In the Symbol combo box, select the
currency appropriate to your country.

9. Repeat steps 6 and 7 to change the DataFormat property of the Total text box to
Currency.

10. Click the Total text box control to select it. On the Properties window, change the
Alignment property to 1 – rptJustifyRight.

11. Save and run the project.

Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
Go to the next step Adding a Function Control to the Data Report
Start from the beginning Creating a Simple Data Report

Adding a Function Control to the Data


Report

The Data Report designer features its own set of controls. Among these, the Function
control has no counterpart among the Visual Basic intrinsic controls and deserves further
explanation.
The Function control displays data that is calculated at run time, using a built-in function,
as the report is generated. A typical example is shown in the figure below, where the

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Function control is used to display the sum of sub-totals to create a total value for a
particular order.
If you have created a calculated field using a SQL statement (in the previous topic,
"Adding a Calculated Field to the Data Report"), you may wonder why a Function
control can't also be used to calculate the value of Quantity * UnitPrice. In short, the
Function control can calculate values only after all other records in a group section have
been processed. In contrast, a SQL statement calculates the values as part of the fields in
a record as they are processed.
The steps to adding a Function control to the Data Report designer are:

1. Draw a Function control in an appropriate Footer section of the Data Report


designer.

2. Set the DataMember and DataField properties to appropriate values (a numeric


field from a relevant data environment Command object.)
Data Report with Function Control Showing Totals

Note This topic is part of a series that walks you through creating a sample data report.
It begins with the topic, Creating a Simple Data Report.
To add a Function control to the data report
1. Using the mouse pointer, click the group footer named Customers_Footer, and
drag it towards the bottom of the window, to create a space between it and the
Orders_Footer footer.

2. On the Toolbox, click the rptFunction control.

3. Draw the rptFunction control in the space between the two footers.

4. Set the properties of the rptFunction control according to the table below:
Property Setting
DataMember OrderDetails
DataField Total
Name fncTotal
Alignment 1 – rptJustifyRight
DataFormat Currency
5.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


6. The FunctionType property of the control determines what operation will be
performed with the data found in the DataField. By default, the property is set to
0-RptFuncSum, to sum the data. Other functions include: Average, Minimum,
Maximum, Row Count, STDDev (Standard Deviation), and Value Count.
7. Draw a Line control just above the Quantity text box, and a Label control to the
left of the text box. Set the Caption property of the label to Total.

8. Click the fncTotal control to select it. On the Properties window, double-click
Font to display the Font dialog box. Change the Font style to Bold.

9. Repeat step 6 with the Label control.

10. Position the controls on the designer to resemble the figure below:

11. Save and run the project.

Increasing the scope of the function


You can increase the scope of the function by placing the control in a lower group footer.
For example, you may want to find out the grand total of each customer's set of orders.

To show a grand total for all orders


1. Draw a new Function control in the Customers_Footer section. Align the new
control with the Function control created above.

2. Draw a Label control to the left of the new Function control.

3. Set the properties of the controls as shown in the table below:


Control Property Setting
rptFunction Name fncGrandTotal
rptFunction DataMember OrderDetails
rptFunction DataField Total
rptFunction Font (Font Style) Bold
rptFunction Alignment 1 – rptJustifyRight
rptLabel Caption Grand Total
rptLabel Font (Font Style) Bold
rptLabel Alignment 1 – rptJustifyRight
4.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


5. The Data Report designer should now resemble the figure below:

6. Save and run the project.

Optional—Adding a Report Total


It's possible to increase the scope of the Function control even further. If you wish to see
a total of all orders in the report, you can add a Function control to the Report Footer
section.

To add a Report Total to the data report


1. Right-click the Data Report designer and click Show Report Header/Footer.

2. Add a Function control to the report footer.

3. Set the property of the control as shown in the table below:


Property Setting
Name fncReportTotal
DataMember OrderDetails
DataField Total
DataFormat Currency
Alignment 1 – rptJustifyRight
4.
5. Note The number for the entire report will be especially large. Therefore the
width of the Function control will have to be adjusted accordingly.
6. Save and run the project.

Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
Go to the next step Grouping Information in the Data Report
Start from the beginning Creating a Simple Data Report

Grouping Information in the Data Report

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Information that is grouped can give the user a different perspective on data. Working in
tandem with the Data Environment designer, the Data Report designer gives you the
ability to group data according to any field in a table. The figure below shows a data
report grouped by countries.

Data Report Grouped By Country

Grouping by Command Field


The grouping field provided by the data environment's Command object differs from the
grouping already achieved by creating group headers and footers. Instead of using the
table of a database as the basis for grouping, the Grouping feature of the Data
Environment designer allows you to select a particular field in the table as the grouping
field without having to create a new Command object.
The steps to adding a grouping field include:

1. Creating a group field in the Data Environment designer.

2. Adding a Group Header/Footer to the Data Report designer to correspond to the


new command.

3. Resetting the DataMember property of the data report to the new Grouping
Command object created in the data environment.

4. Dragging the group field from the data environment to the data report.

Note This topic is part of a series that walks you through creating a sample data report.
It begins with the topic, Creating a Simple Data Report.

To add a grouping field to the Data Report designer


1. In the Data Environment designer, right click the Customers Command object.
Click Properties to show the Customers Properties dialog box.

2. Click the Grouping tab.

3. Click Group Command Object.

4. In the Fields in Command box, double-click Country. Click OK to close the


dialog box.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Notice that the Customers Command object has been renamed as Customers
Grouped using Customers_Grouping, and that two new folders have been
created for the fields. The first, Summary fields in Customer_Grouping
contains the field(s) that the subordinate fields will be grouped by. The
subordinate fields are contained in the second folder, Detail Fields in
Customer_Grouping.
5. Right-click the Data Report designer, and then click Insert Group
Header/Footer.

6. Click the up arrow three times to insert the group header at the outermost edge of
the header/footer pairs. Click OK to close the dialog box.

7. On the Data Report designer, click the new Group Header to select it, and
change its name from Section1 to Customers_Grouping_Header in the
Properties window. Click the new Group Footer to select it, and change its
name to Customers_Grouping_Footer.

8. Click the Data Report designer's title bar to select the entire data report. On the
Properties window, click DataMember and change the property from Customers
to Customers_Grouping.

When the grouping field was added to the data environment, the equivalent of a
new Command object was also added to the data report. That virtual Command
object is displayed in the drop-down list of data members as
Customers_Grouping.
9. In the Data Environment designer, open Summary Fields in
Customers_Grouping. Drag the Country field into the new section on the Data
Report designer.

10. Delete the Label control that accompanies the Country field. Place the new field
at the leftmost edge of the designer, which should now resemble the figure below:

11. Save and run the project.

Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
Go to the next step Adding an Aggregate Field to the Data Report
Start from the beginning Creating a Simple Data Report

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Adding an Aggregate Field to the Data
Report

In the Data Environment designer you can also create aggregate fields—fields that
summarize data from a section. An aggregate field is thus similar to the Function control
in that both are calculated as the report is generated. But there are a few differences:
whereas the Function control can only be placed in a Group Footer, an aggregate field
can be placed in any section of the Data Report designer, except the Report
Header/Footer and Page Header/Footer sections.

Another difference is found in how the two fields are created: while the Function control
is a feature of the Data Report designer, the aggregate field is a feature of the Data
Environment designer. The steps to adding an aggregate field to the report are:

1. Create an aggregate field in the Data Environment designer.

2. From the Data Environment designer, drag the aggregate field onto the Data
Report designer.

As an example, the figure below shows an aggregate field that displays the number of
products ordered.
Data Report with Aggregate Field

Using a Function control can be more efficient than an aggregate field. When the data
report calculates the value for a Function control, it takes a certain amount of processing
to create each value. When the data environment creates an aggregate field, it takes a
similar amount of processing. However, you can save that processing time by using the
Function control because the Data Report designer must create the entire report in its own
process.

Note This topic is part of a series that walks you through creating a sample data report.
It begins with the topic, Creating a Simple Data Report.

To create an aggregate field in the data environment


1. On the Data Environment designer, open the Detail Fields in Customers folder,
and right-click Orders, then click Properties.

2. On the Orders Properties dialog box, click the Aggregates tab.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


3. Click the Add button.

4. Click the Name box and type ProductCount.

5. In the Function combo box, select CNT.

6. In the Aggregate combo box, select OrderDetails (it should be selected by


default).

7. In the Field combo box, select ProductID.

8. Click OK to close the dialog box.

Now that you have created the aggregate field, you can place it on the Data Report
designer.

To Add the aggregate field to the data report


1. From the Data Environment designer, drag the ProductCount aggregate field
onto the group section named Orders_Header.

2. Change the Caption of the Label control to Product(s) Ordered.

3. Reposition and resize the TextBox control and the Label control so the designer
resembles the figure below:

4. Save and run the project.

Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
Go to the next step Grouping Information in the Data Report
Start from the beginning Creating a Simple Data Report

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html

You might also like