TelerikReporting LearningGuide
TelerikReporting LearningGuide
10. Parameterized Reports 11. Sub Reports 12. Styling Your Report 13. Conditional Formatting 14. Reports at Runtime 15. Events 16. Paper Size 17. Handling Report Output
Telerik Reporting
Copyright 2008 Telerik Inc.
All rights reserved. no parts of this work may be reproduced in any form or by any means - graphic, electronic or mechanical, including photocopying, recording, taping or information storage and retrieval systems - without the written permission of the publisher. Products that are referred to in this document may be either trademarks and/or registered trademarks of the respective owners. The publisher and the author make no claim to these trademarks. While every precaution has been takin in the preparation of this document, the publisher and the author assume no responsibility for errors or omissions, or for damages resulting from the use of information contained in this document or from the use of programs and source code that may accompany it. In no event shall the publisher and the author be liable for any loss of profit or any other commercial damage caused or alleged to have been caused directly or indirectly by this document.
Author: Noel Rice Design: Matt Kurvin Acknowledgement: Ivo Nedkov Vassil Terziev Nikolay Dobrev Lino Tadros Todd Anglin Vassil Petev Svetozar Georgiev Production: Falafel Software Inc. www.falafel.com (http://www.falafel.com/)
About Telerik
Telerik Corporation was founded in 2002 and is a leading vendor for award winning ASP.NET and Windows user interface components. Telerik customers include Fortune 500 companies, education, government and nonprofit organizations all over the world: Microsoft, United Nations, US Army, Harvard University, Intel, Siemens,
You have never used Telerik Reporting and want to learn what it is all about. You have used an earlier version of Telerik Reporting and want to become familiar with using the new features. You have used Telerik Reporting and want to make your knowledge more comprehensive.
Windows 2000 Professional Windows 2000 Server Windows XP Home, SP2 Windows XP Professional Windows 2003 Server Windows Vista
IDE: Visual Studio 2005/2008 in Standard, Professional, Team, Express editions. Programming Languages: C# or VB.NET. Also of course, Telerik Reporting must be installed. This will in turn install the AdventureWorks MSSQL database that is required for many of the labs in this courseware.
Telerik Reporting
Copyright 2008 Telerik Inc.
All rights reserved. no parts of this work may be reproduced in any form or by any means - graphic, electronic or mechanical, including photocopying, recording, taping or information storage and retrieval systems - without the written permission of the publisher. Products that are referred to in this document may be either trademarks and/or registered trademarks of the respective owners. The publisher and the author make no claim to these trademarks. While every precaution has been takin in the preparation of this document, the publisher and the author assume no responsibility for errors or omissions, or for damages resulting from the use of information contained in this document or from the use of programs and source code that may accompany it. In no event shall the publisher and the author be liable for any loss of profit or any other commercial damage caused or alleged to have been caused directly or indirectly by this document.
Author: Noel Rice Design: Matt Kurvin Acknowledgement: Ivo Nedkov Vassil Terziev Nikolay Dobrev Lino Tadros Todd Anglin Vassil Petev Svetozar Georgiev Production: Falafel Software Inc. www.falafel.com (http://www.falafel.com/)
Objectives
2. Right-click the project context menu and select Add | New Item | Telerik Report. Enter a name for the report class and click the Add button to close the dialog. In this example we name the report class file "HelloWorld.cs".
3. The Telerik Report Wizard will appear automatically to help you select data and design your report quickly. In this case, click the Cancel button so we can create a "Hello World" report manually with static data. 4. Click Yes to confirm the "Are you sure you want to cancel this wizard?" dialog. You can overwrite your existing report at any time from the Report Wizard option of the Visual Studio Telerik Reporting menu. 5. The Telerik Report designer displays sections for a basic report with a page header, detail and footer. The Toolbox window displays the controls that can be dragged to the report design surface. Later we will dig into more specifics of the report designer and the kind of sections that can be included in the report, and how each type of Telerik Reporting component behaves. 6. Use the mouse to resize the header, detail and footer sections to make each section smaller. The mouse cursor will display drag handles as you pass it over the very top of each section heading and also along the bottom border of the report footer.
10. Double-click the TextBox and edit the text to read "Heading". Note: This step assigns the TextBox Value property.
12. Drop a TextBox component in the Detail section and change the text to "Detail". 13. Drop a TextBox component in the Footer section and change the text to "=PageNumber + " of " + PageCount". Note: We will talk later about how expressions are created, but for now just copy the expression into the TextBox.
16. Now click on the HTML Preview tab to see how the report output will look in a browser. Notice that the HTML rendering does differ from the Winforms preview.
2. Right-click the project context menu and select Add | New Item | Telerik Report. Enter a name for the report class and click the Add button to close the dialog. In this example we name the report class file "ProductList.cs".
3. The Telerik Report Wizard will appear automatically to help you select data and design your report quickly. Once you have the basic report layout you can go back to edit the report, add data columns and tweak the format. Click the Next button.
10
4. On the Report Choice Page of the Report Wizard, select New Report and click the Next button.
5. On the Choose Data Source page of the Report Wizard, select New Data Source and click the Next button.
11
6. On the Choose a Data Source Type page of the Report Wizard select the Database icon and click the Next button.
7. On the Choose a Data Connectionpage of the Reports Wizard click the New Connection... button. 8. In the Add Connection dialog: 1. Make sure the Data source is "Microsoft SQL Server".
12
9. On the Choose a Data Connectionpage of the Report Wizard, verify that yournew database connection for AdventureWorks is selected from the drop down list. Note: The machine name will be the name of the machine you are developing on, i.e. <my machine name>sqlexpress.AdventureWorks.dbo. Click the Next button.
13
10. In the Choose Your Database Objects page of the Report Wizard: 1. Click the Query Builder button. 2. In the Add Table dialog select "Product", "ProductInventory", "ProductPhoto" and "ProductProductPhoto" from the list of tables. Note: You can hold down the control key and click each of the tables to select them all at one time. 3. Click the Add button, then click the Close buttonto close the dialog.
14
6. In the Choose your Database Objects page of the Report Wizard, click the Next button.
15
13. On the Choose Report Layout page of the Report Wizard unselect the Adjust report items to fit available space checkbox. Click the Next button.
16
14. On the Choose Report Style page of the Report Wizard select "Civic" from the Style Sheets list on the left side of the page. Notice the style changes in the Preview portion on the right side of the page.
15. On the Completing the Wizard page of the Report Wizard you can review the settings for the report and click the Finish button.
17
The initial report layout appears in the design view in Visual Studio. Notice that the wizard hasautomatically provided:
Data set adapter and data set components. Data bound fields in the detail section of the report. Styled page and column titles. Apage footer with standard date and page number output.
18
16. Click the Preview tab of the designer to view your report.
19
20
2. In the Solution Explorer, right-click the project References nodeand select Add Reference from the context menu. Select the reference for the class library containing your report from the list on the Projects tab.Note: If the class libraryresides in another solution you will need to use the Browse tab and navigate to the assembly containing the report.
21
Once the report is selected, notice that a component representing the report appears in the tray below Windows form designer. The component allows you to access the properties of the report in your report viewing application, providing access to report parameters, styles and page settings. 6. Add a call to the report viewers RefreshReport() method, just after the call to InitializeComponent() in the form constructor. [C#] Calling RefreshReport() public Form1() { InitializeComponent(); reportViewer1.RefreshReport(); } [VB] Calling RefreshReport() Public Sub New() InitializeComponent() reportViewer1.RefreshReport() End Sub 7. Right-click theWindows report viewing application and selectSet as Startup Project from the context
22
Summary
In this section you used best practices when constructing your reportingsolutions for best code reuse. You created a simple "Hello World" single page report without a database and also you created a simple database listing of products. Finally you displayed your report in a Windows form viewer.
23
Objectives
The Telerik Reporting Menu holds options to display a Report Explorer, Data Explorer and to invoke the Report Wizard. Note: You can also reach the Data Explorer and Report Explorer by right-clicking next to the design area and selecting View from the context menu. The view mode buttons Designer, Preview and HTML Preview appear above the report design surface and control the overall behavior of the designer. The report design surface is the largest area containing report sections that make up the report. Below the report design surface, is a set of tools that allows you easier accessand better control over the design environment.The Zoom drop down lets youenter a percentage or pick a predefined zoom. The next two tools let you toggle the snap-to-grid visibilityand functionality. The Snap to Snap Lines tool when enabled lets you easily align a report item with other items on the design surface. The Dimensions tool displays report item measurements from the item to the edge of the report. The Pan tool when enabled lets you drag the report around the design surface - this can be handy when the report exceeds the easily viewable dimensions of the Visual Studio IDE. The Report Mini-map displays a thumbnail image of the report. Below the report design surface, thecomponent tray may hold one or more data access or group components.
24
Report selector button: Located in the upper left hand of the report designer. Clicking this buttonmakes the report active in the Properties window. Rulers: on the top and left side of the designer provide apoint of reference to the report layout.Click inthe rulerarea to display a line vertically or horizontally across the report.You may also drag in the ruler area to select an area vertically or horizontally across the entire report. This can be particularly useful when you want to select everything in a particular column or set of columns vertically. Report Sections: The high level report design consists of report sections for the report header, report footer, page header, page footer, detail, group header and group footer. You can select sections using the icon to the left of each section. Each section can be resized by dragging the sizing grips at the top of each section and collapsed using the button located to the left of each section. Most sections except the detail can be deleted by selecting the section and hitting the delete key. ContextMenu: This menu will conditionallydisplay contents depending on the area that was right-clicked.
Here is another view of the Report MiniMap showing how you candrag a box representing the visual area of the report:
25
Report Explorer
The Report Explorer is an aid to navigating report elements.The Report Explorer allows you to see the structure of the report and to select any item in the report.The Report Explorer can be especially handy for complex reports where components may be nested and where it would be difficult toselect an item with the mouse. The Report Explorer can also be accessed from thecontext menuView | Report Explorer item when rightclicking the area next to the report design surface. In Visual Studio, open the report project you built in the "Creating a Simple Database Report" tutorial. If you don't see the Telerik Reporting menu, click on the report design surface and it will appear. The Report Explorer shows a tree representation of the sections within the ProductList report class (i.e. page header, report header, etc.) and the report items within each section. Clicking on report sections and items places focus on the corresponding entry. Try clicking the "detail" entry in the Report Explorer. Notice that the section title bar gets focus as you select it in the Report Explorer. Also try selecting report items.
26
Data Explorer
The Data Explorer window lists the data source columns defined for your report. You can drag column names from the Data Explorer to the report design surface. The report designer automatically creates appropriate report items based on the column data type, e.g. if the column has character data a TextBox report item will be created, if the column has image data then a PictureBox report item will be created. Using the "Creating a Simple Database Report" tutorial project, open the Data Explorer. Drag the "Name" column to the Detail section of the report designer.Notice that this action automatically creates a TextBox report item.Now try dragging the ThumbNailPhoto column to the Detail section of the report. This time a PictureBox report item is created. Double-clicking a Data Explorer column name will create a report item in the currently selected report section. Try selecting the PageHeader, then double-click the "Name" column.
27
Report Wizard
The Telerik Report Wizard helps you quickly create your report structure.You can also convert existing Crystal, ActiveReports or Developer Express XTra Reports to the Telerik Reporting format. The wizard walks you through selecting, arranging and formatting the data for the report.The Report Wizardruns automatically when you add a Telerik Report item to the project, but can also be run from the Telerik Reporting menu. Each run of the Report Wizard overwrites previous definitions of the report.
Report Sections
Your report layout will typically include multiple sections and always at least one detail section (the detail section cannot be removed).
28
Report paging strongly depends on the format it is rendered to. Page header and footer sections are processed by a rendering extension after the report data has been processed. At this moment the report data source is not available anymore and you cannot add databound items directly to these sections. For this same reason, you can use the built-in PageNumber and PageCount objects only in these sections.
Any control you place in the report header section is rendered once at the top of the entire report's output, but after the first page header section (if any). Any control you place in the report footer section is rendered once at the bottom of the entire report's output, but before the last page footer section (if any). Why does the page header print before the report header? A report can be viewed as "document content", consisting of detail, report header and footer sections. Similar to Microsoft Word, document content is centered on the screen with page header and footer sections above and below the content. Page headers and footers are not related to the report itself, but are relative to the margins of the report's media, i.e. to the paper or screen. Usually page headers and footers are placed in the margins and contain page numbers, document dates, etc.
Groups
You can group data in the report so that some change in data triggers a break in the report.For example, if a product listing report has a product category and subcategory, the report can show first the category, then subcategories below it. Each Group has a GroupHeaderSection and GroupFooterSection associated with it.TheGroupHeaderSection printsat the beginning of each groupandtypically hasa name or description of the group. The GroupFooterSection prints after the detail data for the group and can contain summary data. You can output aggregate functions (e.g. totals, counts, etc). Each group can be filtered and sorted. In the Group header and footer sections all data fields must be aggregated, even if the data source returns only one row. Typically you should use the FIRST() function for character and date data and the SUM() function for numeric data. When you place a databound report item that uses an aggregate function in the Group Header, it is calculated for the entire group data.
Detail
The Detail section is always present for every report. For reports bound to data, a detail section will output for every database record. This is where you place the report items that make up the main body of the report.
Report Items
Report itemsare found in the Visual Studio Toolbox window and are dragged onto the report design surface to contain report content.
29
Chart: The chart lets you display data in a visually compelling way. The chart can bind to live data and display in many popular chart types, e.g. Bar, Pie, Gantt, Line, Area, Bubble, etc. Panel: The Panel report item is used to group multiple report items together. PictureBox: The PictureBox allows you to place images in the report using bitmap files (e.g. bmp, gif, jpg, png, ico). Shape: The Shape item displays visual primitives in the report including ellipse, vertical/horizontal/slanting lines, and triangles. SubReport: The SubReport report item lets you display one report within another report. This allows you to compose complex reports fromdisparate report sources. TextBox: The TextBox displays text in the report, can be styled to a specificvisual appearance,can be configured to grow/shrink, formatted for specific data types (e.g. date time) and can be multi-line.
The TextBox in-place editor allows you to quickly enter text directly into the designer where the report item is rather than having to go look for a property in the Property Window. To activate the in-place editor, double-click the TextBox report item or select the report item and press F2. Once the in-place editor is activated:
CTRL-Enter creates a new line. Enter accepts all changes. Esc discards all changes. Moving focus away from the TextBox also accepts all changes.
30
Grab and drag the resizing handles from any size or corner of the report item:
Notice the small curved lines around each corner. These allow you to drag and rotate a report item. As the item is rotated, a circle appears showing the area that the item is being rotated within. The outside edge of the circle displays a tiny red dot and a figure indicating the number of degrees that the item is being rotated.
Dynamic Layout
Anchoring and Docking properties have long been available to WinForms applications.Telerik Reports brings this feature to the reporting design environment.Using Anchoring and Docking you can create table-like report layouts all items inside a section can grow equally regardless of their content thus forming the columns of a table. Dynamic layout comes into play when the container can be resized, for example when:
A child TextBox item with theCanGrow property enabled can grow in height to accommodate long strings of text. A SubReport item can grow in width and height according to the source report it contains. A PictureBox item with auto sizing enabled (PictureBox.SizingMode= AutoSize) can grow to fit a bigger image.
Anchoring is used to dynamically resize report items with their container, i.e. Panel or section.As the container is resized,the report item will maintain a constant distance between its edges and the corresponding edges of the container.
31
Docking a report item causes its edges to adhere to the edges of its container. When a report item is docked to an edge of its container, it is always positioned flush against that edge, evenwhen the container is resized.
The example below has a page header section with two docked TextBox items, the first docked to the Top of the section, the second docked to Fill the remaining space in the section. In the detail section a TextBox item is anchored with top and bottom edges not quite touching. As the section is resized, the TextBox maintains its relationship to the top and bottom edges.
32
33
Objectives
IEnumerable: e.g. System.Array, IList, ICollection, and BindingSource IListSource: e.g. DataTable and DataSet ITypedList: e.g. DataView and DataViewManager IDbDataAdapter: e.g. SqlDataAdapter and OleDbDataAdapter Telerik Reporting does not have its owndata layerbut depends on the existing .NET objects (DataSet, Data Table, DataView, ADO.NET, listsetc.) For example, if you are connecting toa stored procedure you will end up returning an object that can be used as a data source, e.g. a DataSet, DataView, DataReader, etc. For more specifics on connecting to stored procedures please see Microsoft knowledge base articleCall a Parameterized Stored Procedure by Using ADO.NET... (http://support.microsoft.com/kb/310070)
You can assign these data source types through the Report Wizard, manually at design time or programmatically at run time. At the simplest level you could create an array or generic list of a simple object and bind it to the report. For example, let's say we have a report definition with only a detail section. The detail section contains only a singleItem Binding Expression. We will cover Item Binding Expressions shortly, but for now, see the expression in the screenshot below "=Fields.Name".
When the report is bound, the data for the "Name" property of thedata sourcewill be output.
34
The code to get this done can be as simple as the example below where a generic list is created, populated and assigned to the report DataSource property. The generic list contains a series of Product objects. "Product" is the mostminimal class possible and contains only a single "Name" property. [C#] Populating and Assigning a DataSource using System.Collections.Generic; public partial class ProductList : Report { public ProductList() { InitializeComponent(); // Create a generic list of Product and // add sample products List<Product> products = new List<Product>(); products.Add(new Product("bicycle")); products.Add(new Product("helmet")); products.Add(new Product("shoes")); // Assign the generic list as the report DataSource this.DataSource = products; } } // A very simple class with a single Name property public class Product { private string _name; public Product(string name) { _name = name; } public string Name { get { return _name; }
35
36
5. Right-click the designer and select "View Code" from the context menu. 6. Add a "Coffee" class: [C#] Simple Class With Two Properties public class Coffee { private string _name; private int _id; public Coffee(string name) { _name = name; } public string Name { get { return _name; } set { _name = value; } } public int ID { get { return _id; } set { _id = value; } } } [VB] Simple Class With Two Properties Public Class Coffee Private _name As String Private _id As Integer Public Sub New(ByVal name As String) _name = name End Sub Public Property Name() As String Get Return _name End Get Set _name = value End Set End Property Public Property ID() As Integer Get Return _id End Get Set
37
4. The Data Source Configuration Wizard starts at the Choose a Data Source Type page. Here you can choose between a standard database (e.g.MS SQL, Access, Oracle, etc.) or a Business Object that acts as a middle tier for data. In this example, click the Database icon, then click the Next button.
39
5. In the Choose a Data Connection page of the wizard, you can select a previous connection from the drop down list or create a new connection. Click the New Connection button.
6. In the Add Connection dialog, verify that the Data Source is "Microsoft SQL Server (SqlClient)". If not, click the Change button to select a different data source provider. To the Server Name entry add "<your machine name>\SQLEXPRESS". In the Connect to a database box, make sure the radio button labled "Select or enter a database name:" is selected, drop down the list and select the "AdventureWorks" database. You
40
7. Closing the Add Connection dialog brings you back to the Choose a Data Connection page of the wizard.Make sure that the connection you created is selected from the drop down list. Click the Next button to continue.
41
8. In the Choose Your Database Objects page of the wizard, you can enter SQL directly or click the Query Builder. The Query Builder dialogautomatically displays the Add Table dialog. From there you can select one or more tables, views, functions or synonyms to be included in the query. Query Builder alsohas an Execute Query button so you can "audition" the data.
42
9. In this case, add the following SQL to the Choose Your Database Objects page of the wizard: [SQL] Adding theVendor ContactsQuery SELECT Purchasing.Vendor.AccountNumber AS [NUMBER], Purchasing.Vendor.NAME AS [Account], Person.Contact.FirstName AS FIRST, Person.Contact.LastName AS LAST, Person.Contact.EmailAddress AS Email, Person.ContactType.NAME AS [TYPE] FROM Purchasing.VendorContact INNER JOIN Purchasing.Vendor ON Purchasing.VendorContact.VendorID = Purchasing.Vendor.VendorID INNER JOIN Person.Contact ON Purchasing.VendorContact.ContactID = Person.Contact.ContactID INNER JOIN Person.ContactType ON Purchasing.VendorContact.ContactTypeID = Person.ContactType.ContactTypeID 10. Click the Finish button to complete and close the wizard. 11. Open the Telerik Reporting menu and select the Data Explorer. Note: if you don't see the Telerik Reporting menu, click on the report design surface - the menu will appear. 12. Drag fields"Number" and "Account" to the Detail section of thereport.
43
13. Drag a TextBox report item from the ToolBox window to the Detail section of the report. 14. Double-click the TextBox and enter '=Fields.First + " " + Fields.Last'. This will output the concatenated first and last names of the contact name. 15. Drag the other fields "Type" and "Email" to the Detail section of the report.
16. Now drag TextBox report items from the ToolBox window to the Page Header section of the report. Drag one TextBox per field and name the columns "Account Number", "Account Name", "Contact", "Type" and "Email".
17. Click the Preview tab to view the report. Notice that the Page Header text outputs at the top of each page, with multiple detail lines on each page. Also notice that the contact name has the concatenated first and last names.
44
45
Summary
This section defined the underlying types of data that can be bound. You learned how to bind very simple array type data. You also learnedhow to bind database data manually and programmatically.
46
Objectives
47
Be aware that not all expressions are available in all sections of the report. For example, PageCount and PageNumber are only available in the page header and footer. These issues will be discussed in more detail during the "Report Life Cycle" discussion that follows later in this tutorial.
User Functions
If the rich set of built-in expressions are not getting the job done, you can create your own user function for consumption directly in your expressions. User functions are defined per report, can be used in any expression (item value, filters, grouping, sorting, conditional formatting) and can be used at design time or run time. User functions are public static (Public Shared in VB.NET)methods of the report classthat always return a value. As long as the function is public, static and returns a value, you have complete flexibility in your implementation. The example below formats an address based on city/state/zip passed in as parameters. [C#] Defining a User Function public partial class Report1 : Report { //.. public static string FormatAddress(string city, string state, int zip, int zipPostfix) {
48
The results of the user function in an expression can be viewed immediately in the Preview tab.
49
50
4. The Data Source Configuration Wizard starts at the Choose a Data Source Type page. Here you can choose between a standard database (e.g.MS SQL, Access, Oracle, etc.) or a Business Object that acts as a middle tier for data. In this example, click the Database icon, then click the Next button.
51
6. In the Add Connection dialog, verify that the Data Source is "Microsoft SQL Server (SqlClient)". If not, click the Change button to select a different data source provider. To the Server Name entry add "<your machine name>\SQLEXPRESS". In the Connect to a database box, make sure the radio button labled "Select or enter a database name:" is selected, drop down the list and select the "AdventureWorks" database. You can click the Test Connection button to verify that everything works. Click OK to close the Add Connection dialog.
52
7. Closing the Add Connection dialog brings you back to the Choose a Data Connection page of the wizard.Make sure that the connection you created is selected from the drop down list. Click the Next button to continue.
53
8. In the Choose Your Database Objects page of the wizard, you can enter SQL directly or click the Query Builder. The Query Builder dialogautomatically displays the Add Table dialog. From there you can select one or more tables, views, functions or synonyms to be included in the query. Query Builder alsohas an Execute Query button so you can "audition" the data.
54
9. Add the following SQL to the Choose Your Database Objects page of the wizard: [SQL] List Vendor Contacts SELECT top 20 Production.Product.NAME, Production.WorkOrder.StockedQty, Production.WorkOrder.ScrappedQty, Production.WorkOrder.OrderQty FROM Production.Product INNER JOIN Production.WorkOrder ON Production.Product.ProductID = Production.WorkOrder.ProductID WHERE Production.WorkOrder.ScrappedQty > 0 10. Click the Finish button to complete and close the wizard. 11. Right-click the report designer and select View Code from the context menu. Add the following user function to the report class: [C#] Defining the User Function public static double ScrappedPercent(int totalQty, short scrappedQty) { return Convert.ToDouble(scrappedQty) / Convert.ToDouble(totalQty) ; }
55
16. Right-click the "tbPercent" TextBoxand select Expression... from the context menu. 17. Click User Functions from the list on the lower left. Double-click the "Scrapped Percent" user function from the list on the right. Your expression should look something like the screenshot below:
56
18. Click Fieldsfromthe list on the lower left. 19. Double-click "OrderQty" from the list on the right. 20. Manually enter a comma. 21. Double-click "ScrapQty" from the list on the right.
57
22. Click OK to close the Edit Expression dialog. 23. With "tbPercent" still selected, locate Format in the Properties window and click the ellipses to display the Format Builder dialog. Note: The Format Builder helps you create format strings that can be applied against your data. The dialog comes with a number of commonly used formats for numbers, currency, date/time, etc., or you can build your own custom format string. 24. In the Category list select "Custom". In the Format list select "0.00%"
58
25. Click the Preview tab to view the report. Notice the Scrapped % column data is properly formatted.
Summary
This section reviewed the types of expressions available,how to create your own user defined functions and how to assign expressions at design-time
59
Objectives
In this lesson you will learn how groups act on report data, andhow to create groups at both design time and run-time.
Grouping Overview
Groupstrigger breaks in the report based on changes in report data.Youcan havemultiple levels of grouping nested within a report. Below is a sales report example with columns for "Region", "Territory", "Stores" within territories and total sales for each store. Each region is grouped so that "US" has its own subtotal. Below that, each territory "Northeast" and "Southwest"has its own count of stores and subtotal for total store total sales.
60
Name:A descriptive name such as "regionGroup". Filters:This propertydetermines which groups will display.This level of filtering occurs before filtering for the report as a whole occurs.The filters for the group are applied to the grouping data, not the report data itself. GroupKeepTogether: If this property is set to FirstDetail, then the group header and the first detail record are printed on the same page of output. A setting of All ensures that the entire group is printed on the same page of output. If there is not enough space on the current page, then rendering will skip to the top of the next page. Grouping:This property controls grouping criteria that determine where the grouping level breaks occur. Sorting:This property controls the sorting order for the grouping data, not the report data. This level of sorting occurs before the sorting for the report as a whole.
KeepTogether: If True the entire section remains together on one printed page if possible. If there is not enough space on the current page, then rendering will skip to the top of the next page. PageBreak: Specifies where to put page breaks relative to this group, i.e. None, Before, After, or BeforeAndAfter.
61
PrintOnEveryPage: If True the group header is repeated at the top of each page. Visible: Set to False to prevent the group from rendering. ConditionalFormatting: A collection containing rules and formatting to be applied to this report item if the rules succeed.
Using the Design Data Layout page of the Report Wizard. Use this method when you need to set both the grouping and the general characteristics of the entire report quickly. Right-clicking the designer and selecting Add New Group from the context menu. Use this method to quickly add another grouping to an existing report. Clicking the menu option displays the Edit Grouping dialog where you can specify criteria for the grouping.
Using the Groups collection of the report object. This method gives you greatest control over all the grouping related properties at one time.
62
Create a Group object Create and assign a Grouping object to the group. The Grouping object includes the expression used by the group to know when the report break should occur. Create group header and footer sections. Create and assign report items to the group header and footer sections.
The example below takes a simple list of territories, stores within territoriesand total sales for each store. The query below defines the data: [SQL] TerritorySales SELECT TOP (50) Sales.SalesTerritory.NAME AS Territory, Sales.Store.NAME AS Store, Sales.SalesOrderHeader.TotalDue AS Total FROM Sales.SalesOrderHeader INNER JOIN Sales.SalesTerritory ON Sales.SalesOrderHeader.TerritoryID = Sales.SalesTerritory.TerritoryID INNER JOIN Sales.Store ON Sales.SalesOrderHeader.CustomerID = Sales.Store.CustomerID INNER JOIN Sales.CustomerAddress ON Sales.SalesOrderHeader.CustomerID = Sales.CustomerAddress.CustomerID This example assumes that you already have a simple report with detail only against this data and want to group on "Territory". In the code example below we create groups, group header and footer sections and report items. [C#] Creating Group, Sections and Report Items
63
64
Summary
This lesson demonstrated the basic usage of groups and grouping related properties, how to create groups using the designer and how to create groups using code only.
65
Objectives
Filter Behavior
Filterslimit the number of records in a report based on one or more filter rules.If the rule conditions are met, the record is included in the report. Filters are defined using the the Edit Filter Dialog and can also be created in code.
66
67
68
69
Expression can be a data field from the Fields collection or defined using the Edit Expression dialog. Operator can be simple comparison operators but can also include Like and additional operators to include the top and bottom number of records and the top and bottom percentage of records. The full list of operators are: >, <, >=, <=, =, Like, Top N, Bottom N, Top %, Bottom % and IN. Use Like with the "%" wildcard to represent any number of characters. Top N and Bottom N return a certain number of records. If Expression is blank the filter returns the exact number of records specified by Value.For example "Top N 5" returnsexactly five records.If Expression contains a field or expression the filter returns the top number for that expression. This filter may return more than the exact count specified in Value. For example "ProductCategory Top N 2" might return twenty records containing ProductCategory "Accesories" and "Apparel". Top % and Bottom % work in a similar way. If Expression is blank the filter returns the percentage of total records specified in Value. If the report has an initial 1000 records and the filter is "Top % 5", 50 records are returned. Likewise, if Expression contains a field or expression the filter returns the top percentage records that satisfy the expression. For example if the top two percentcountry codesin a StateProvince table are "AS", "AU" and "CA", the filtermight returntwenty records containingonly thosecountry codes.
Value can be a literal value, "<blank>" or an expression defined in the Edit Expression dialog.
70
71
12. In the Choose Report Layout page of the wizard, click the Next button.
72
15. Delete the TextBox on the right of the report that contains the ThumbNailPhoto binding expression. 16. Drag a PictureBox report item to replace the TextBox. 17. Right-click the PictureBox report item and click Expression... from the context menu. 18. In the Edit Expression dialog, click Fields in the list on the lower left. This will display the database fields currently available in the list on the right. Double-click "ThumbNailPhoto" to add the field name to the item binding expression. Click OK to close the Edit Expression dialog. 19. Click in the report design area outside the sections to select the Report object. 20. In the Properties window, locate the Filters property and click the ellipses. The Edit Filters dialog will display. 21. Click the New button to create a new filter rule.Make the rule settings: Expression: "=Fields.ListPrice" Operator: "<" Value: "100" 22. Click OK to close the Edit Filters dialog. 23. Click the Preview tab to view the report so far. The output should show products with a list price of less than $100, and will show images if they are available.
73
24. Now locate the "subCategoryGroup" component in the component tray and select it with the mouse. 25. In the Properties window, locate the Filters property and click the ellipses. The Edit Filters dialog will display. 26. Click the New button to create a new filter rule.Make the rule settings: Expression: "=Fields.SubCategory" Operator: "Like" Value: "C%" 27. Click OK to close the Edit Filters dialog. 28. Click the Preview button to see the final report. Now you will see data where the sub category starts with a "C" character and where the list price is less than $100.
74
75
Performance Considerations
It's convenient to create complex selections right within Telerik Reports, but it doesn't always perform as well as SQL running on a dedicated server machine. One approach is not inherently better than another.Is there a simple rule to know when sorts and selects should be performed at the database vs. performed in the reporting engine? Not really, but there are some guidelines to help you make the best judgement. Consider the tradeoff between user selections applied at the database vs. selections applied to data at the report level. With large amounts of database server data you need to retrieve the smallest usable set of data to reduce network traffic, use resources effectively and to render reports quickly.
Selections applied at the database level are effective when the data does not need to be re-queried. This can be effective when only a narrow range of data is required. Additional trips to the database for different views of the same data increase the network traffic cost and increase the time needed to render the report. When user selections are applied at the report level the data is cached in-memory. This can be effective when different views of the same data are required and the data is not too large.
A combination of these techniques may be the most appropriate solution. For example, consider sales data that includes sales person and sales date information. The selection at the database could query for a given date range and selections for particular sales people could be applied at the report level. The individual requirements of the report help determine the best solution. Sorting also raises similar performance issues.
76
77
Objectives
Sorting Behavior
Sorting can be performed at the group and report level through the Sorting property.Each sort has an Expression and a Direction. Expression can be a data field from the Fields collection or an expression defined using the Edit Expression Dialog. Direction can be either "Asc" (ascending) or "Desc" (descending). Sorting order is defined using the Sorting property Edit Sorting dialog at design time, or at runtime you can use the report or group's Sorting collection directly.
Un-sorted Report
Reports display data in the order that it comes from the data source. If the data source uses a query with an "order by" clause, then the data will be sorted in the report output. If the data source sends data in the same order that records were input to the database, likewise, the data will display as un-sorted. In this next example, a vendor listing displays state, city and vendor name in no particular order.
78
79
Each sorting expression is made up of an Expression and a Direction. Expression can be a data field from the Fields collection or defined using the Edit Expression dialog. Direction can be Desc or Asc.
80
12. In the Choose Report Layout page of the wizard, click the Next button. 13. In the Choose Report Style page of the wizard, select "Corporate" and click Next. 14. In the Completing the Wizard page of the wizard, click the Finish button to close the wizard. The designer should now look something like the example below.
81
15. Double click the TextBox "Report1" in the report header section. Enter "Vendor Listing". 16. Click in the report design area outside the sections to select the Report object. 17. In the Properties window, locate the Sorting property and click the ellipses. The EditSorting dialog will display. 18. Click the New button to create a new sort expression.Make the expression settings: Expression: "=Fields.City" Direction: "Asc" 19. Click the New button to create a second sort expression.Make the expression settings: Expression: "=Fields.Vendor" Direction: "Asc" 20. Click OK to close the Edit Sorting dialog. 21. Click the Preview tab to view the report so far. The output should show vendors listed within state and city. The city and vendor are sorted in ascending order with vendor sorted within city. Coincidentally, the first two instances of "State" appear to be in ascending order, but this happens to be the default order. Next we will sort the State grouping to change that.
22. Now locate the "stateGroup" component in the component tray and select it with the mouse.
82
83
Summary
This section explored how sorting works against report detail data and how you can also sort groups. You learned how to applysorting at design time and programmatically.
84
Objectives
In this section you will learn how parameters work with expressions to amplify the power of Telerik Reporting. You will see how parameters can make your reporting infrastructure easier to maintain and more flexible for your users. This section also explains the new features of parameters including the automatic parameter UI and Cascading parameters. When you're done creating your parameterized reports, we will create a Windows application that displays the report, and will automatically display parameter prompts for the user.
Parameter Basics
Report Parameters allow users to tailor their own data.Parameters are particularly powerful when coupled with expressions and can be used with filtering, sorting and grouping. Parameters help make your reporting infrastructure flexible and generic.Your customers will be able to get more done beforeneeding maintenancehelp or before you are forced to modify similar but not-quite-the-same reports ("Say, now can you filter that by customer?"). Telerik Reporting supports Boolean, DateTime, Integer, Float and String, or collections of any of these types. Define your parameters at design time using the ReportParameter Collection Editor or at runtime using the ReportParameters collection. Users can also enter parameter values directly into the automatically created UI of the Report Viewer. The SubReport item also has a Parameters collection that can be used for master/detail or other kinds of aggregated reports.
85
When you click OK to close this dialog, the parameter becomes available in any expression throughout the report.
86
1. Create a new report class using the AdventureWorks database and the query below. Include all the fields from the query in your report. [SQL] Vendor Listing Query SELECT Purchasing.Vendor.NAME AS Vendor, Person.StateProvince.StateProvinceCode AS State, Person.Address.City, Person.Address.AddressLine1 AS Address, Person.Address.PostalCode FROM Purchasing.VendorAddress INNER JOIN Purchasing.Vendor ON Purchasing.VendorAddress.VendorID = Purchasing.Vendor.VendorID INNER JOIN Person.Address ON Purchasing.VendorAddress.AddressID = Person.Address.AddressID INNER JOIN Person.StateProvince ON Person.Address.StateProvinceID = Person.StateProvince.StateProvinceID 2. Using the designer, select the report and locate the ReportParameters property in the Property Window. 3. Click the ReportParameters ellipses to display the ReportParameter Collection Editor dialog. 4. Click the Add button to create a parameter. 5. Set the parameter Name as "StateSelect", Type as String and Value as "AZ". 6. Click OK to close the ReportParameter Collection Editor dialog. 7. Locate the report Filters property in the Property Window and click the ellipses to open the Edit Filters dialog. 8. Click the New button to create a new filter rule. 9. In the Expression column of the filter rule select "<Expression>" from the drop down list. The Edit Expression dialog will display. 10. In the lower left hand list of the Edit Expression dialog, select Functions.
87
13. Click OK to accept the new expression and close the dialog. 14. Leave the Operator column of the filter rule as "=". 15. Choose "=Parameters.StateSelect from the Value drop down list.
16. Click OK to close the Edit Filters dialog. 17. In the designer, click the Preview tab. The report will now only show records where the State is "AZ" as defined by our "StateFilter" parameter.
88
Automatic Parameter UI
Instead of changing a ReportParameter Value at design time or coding it, user input can be collected for you automatically. Based on your configuration of the report parameters,a user interface is generated within the designer Preview tab or in a report viewer.
89
Multiple Values
With one minor tweak you can filter against a list of values. Set the UI.MultiValue property to True and the parameter will accept a comma-delimited list of values. You also need to change the expression that employs the parameter so that the "In" comparison operator is used.
90
Now the report preview shows a new editor that lets you edit multiple values, and the report output lists multiple states that match:
To pre-populate the the list of values in code, assign an ArrayList to the Value property: [C#] Populating the Value ArrayList list = new ArrayList(); list.Add("CA"); list.Add("OR");
91
To get a list of values from the database, assign the ReportParameter DataSource property. You can use the ReportParameter DataSource property editor Add Project Data Source option to create a new datasource from scratch.
92
When you define your data source, you can create a simple query against your master data to form a list, for example: [SQL] Query to List State and Province Codes SELECT RTRIM(LTRIM(StateProvinceCode)) AS State FROM Person.StateProvince After you set the DataSource property for the parameter, set the DisplayMember property to a column that will show in the drop down list. Set the ValueMember to the column that should be retrieved when the user selects an item from the list. In this case, we are using the "State" code for both value and display members. Note: If your DataSource contains multiple tables, you also need to select a DataMember.
93
Cascading Parameters
Cascading parameters allow you to have dependencies between parameters so that large amounts of data can be progressively narrowed down.Thistechnique is typically used against data that forms a hierarchy, i.e. country/region/city, header/detail/line items, warehouse aisle/bay/bin, etc. The user experience is that the user chooses from the top-most level of data first, for example "Australia" for country. Then the user has access to regions andcan choose "New South Wales". When the user clicks the Preview button, they can see a list of all cities within the New South Wales region.
1. To recreate the example report shown in the screenshot above, start by creating a new report class based on the SQL below. [SQL] List Country/Region, State/Province andCity SELECT DISTINCT Person.StateProvince.CountryRegionCode, Person.StateProvince.StateProvinceCode,
94
2. In the Property Window, locate the ReportParameters property and click the ellipses. 3. In the ReportParam Collection Editor dialog, add a new parameter. 1. Set the Name property to "CountryRegionParam". 2. Open the UI sub-property, set the Text property to "Country/Region" and Visible to True. 3. Open the UI.AvailableValues property and locate DataSource. Drop down the DataSourceproperty and click the Add Project Data Source option. 4. Create the new data source using the SQL below. The SQL produces a list of country names along with two character codes. [SQL] List Country/Region SELECT NAME, CountryRegionCode FROM Person.CountryRegion 5. With the DataSource set, drop down the UI.AvailableValues.DisplayMember property and select "Name". Likewise, drop down the list for UI.AvailableValues.ValueMember and select "CountryRegionCode". 6. Set the UI.AvailableValues.Sorting property to "=Fields.Name Asc". The parameter properties should now look like this screenshot:
95
4. In the ReportParam Collection Editor dialog, add a second parameter. 1. Open the UI sub-property, set the Text property to "Country/Region" and Visible to True. 2. Open the UI.AvailableValues property and locate DataSource. Drop down the DataSourceproperty and click the Add Project Data Source option. 3. Create the new data source using the SQL below. The SQL produces a list of country/region, state/province names and two character state/province codes. [SQL] List State/Province SELECT CountryRegionCode, NAME, StateProvinceCode FROM Person.StateProvince 4. With the DataSource set, drop down the UI.AvailableValues.DisplayMember property and select "Name". Drop down the list for UI.AvailableValues.ValueMember and select "StateProvinceCode". 5. Set the UI.AvailableValues.Sorting property to "=Fields.Name Asc". 6. Click the UI.AvailableValues.Filters property to display the Edit Filters dialog. Add a new expression where the Fields.CountryRegionCode is equal to the Parameters.CountryRegionParam.This step produces the cascading effect between countries and state/provinces.
96
5. Close the ReportParam Collection Editor dialog. 6. In the Edit Filters dialog for the report, add two filter expressions as shown in the screenshot below. This step matches the report output to the parameter values:
97
7. Click the Preview tab and experiment with the automatically created, cascading drop down lists.
Create a windows or web application. Add a ReportViewer control to the form or web page. Add a reference to the assembly that holds your report assembly. Assign the Report property to one of the reports in your assembly. All reports defined in your assembly show up in the Report property drop down list.
Use the class library for the previous "Cascading Parameters" project as a starting point. 1. Add a new Windows Application project to the Visual Studio solution. 2. Add a reference to the "Cascading Parameters" assembly.
98
3. Add a ReportViewer control to the default form. 4. In the Properties window, locate the Report property and drop down the list. Select the report that contains the "Cascading Parameters" example. When you choose a report, a component representing the report will be created automatically in the component tray. This component allows you to access all the settings of the report including parameters, sorting, grouping and filtering. In this example, you don't need any of this because the UI will be populated automatically without further work on your part. 5. In the Solution Explorer, right-click your viewing application project and select Set as StartUp Project. 6. Press F5 to run the application. 7. In the viewer, click the refresh button ( ).
If you absolutely must code something, you can handle the refresh in code if you like. In theForm_Load event handler, add: [C#] Refreshing the Report private void Form1_Load(object sender, EventArgs e) { reportViewer1.RefreshReport(); } [VB] Refreshing the Report Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) reportViewer1.RefreshReport() End Sub
99
Summary
In this section you learned how parameters work with expressions to create dynamic, powerful and maintainable reports. You learned to create parameters at design-time and run-time.You also learned to automatically include simple and cascading parameters in your user interface. We created a report viewing winforms application that automatically displays parameter prompts.
100
Objectives
This section demonstrates how a SubReport item is used to display one report within another report, allowing you to compose complex reports frommultiple report sources. You will learn how to create aggregate reports from disparate report sources, master-detail reports and how to hide SubReports based on expression criteria.
SubReport Basics
The SubReport report item lets you display one report within another report. The data for each SubReport within a master report can be completely different. The screenshot shows a SubReport at design-time.
Master/Detail reports: This is a very common use where a SubReport are placed in the detail of the master report and passed parameters to define what data the SubReport should display. Aggregate reports: When you have different batches of data that all need to be displayed in the same report, you can use a SubReport to include each collection of data. For example youcould combine a product listing, a sales summary and a list of sales people each in their own sub reports, with each sub report getting data from a different source.
Some of the significant SubReport properties include: Property Description The report to display as a SubReport. Click in this property, and then click the drop ReportSource down button to select a report from the list. Visible Set to False to suppress the display of the SubReport. A collection containing rules and formatting to be applied to this SubReport if the rules ConditionalFormatting succeed. Location Specifies the X and Y coordinates of the SubReport . Size Specifies the Width and Height properties of the SubReport. This collection is used to specify the ReportParameters property of the report being Parameters shown (i.e. the report specified in the ReportSource property). Page Settings: By design, if a subreport is nestedina report,the subreport page settings are ignored (including paper kind/size, orientation and margins) and only the top-level report page settings are used.
101
1. Create a class library project, then a new Report class and name it DepartmentList.cs. 2. Using the Report Wizard, create a simple listing of departments using the SQL below against the AdventureWorks database. [SQL] List Departments SELECT NAME AS Department FROM HumanResources.Department
102
6. Create a new report called JobCandidate.cs and the using the Report Wizard, create a list of job candidates using the SQL below against the AdventureWorks database. [SQL] List Departments SELECT Person.Contact.FirstName, Person.Contact.LastName, Person.Contact.EmailAddress, Person.Contact.Phone FROM HumanResources.Employee INNER JOIN Person.Contact ON HumanResources.Employee.ContactID = Person.Contact.ContactID INNER JOIN HumanResources.JobCandidate ON HumanResources.Employee.EmployeeID = HumanResources.JobCandidate.EmployeeID 7. Add a Shape report item to the page header.Set the ShapeType property to be Horizontal Line. 8. Remove the page footer section. 9. The report designer should look something like this screenshot:
10. Press F6 to rebuild the application. This step will make the DepartmentList and JobCandidates classes available to the SubReport items. 11. Create a third report and name it "Master.cs". Cancel the Report Wizard. 12. In the detail section of the report, add two SubReport items, one above the other. 13. Select the top SubReport and locate the ReportSource property in the Property window. Select the "DepartmentList" report from the drop down list. 14. Select the bottom SubReport and locate the ReportSource property in the Property window. Select the "JobCandidates" report from the drop down list.
103
15. Click the Preview tab to view the master report and its sub-reports.
104
8. Edit the Filters property so that only records where the DepartmentID is equal to the DepartmentID parameter are displayed.
105
106
10. Again, select the SubReport and locate the ReportSource property from the Property Window. Select the EmployeeDetail report from the dropdown list. 11. Edit the SubReport Parameters property. Add a new parameter where DepartmentID is equal to Fields.DepartmentID. This step passes the current DepartmentID for the detail row to the SubReport, where the DepartmentID is used for filtering.
107
108
2. Select the TextBox in the ReportHeader that is labeled "Departments". Set the Value property to this expression: =IIf(Parameters.ShowEmployees, "Department/Employee", "Department") You can enter it directly or use the Edit Expression dialog:
109
3. In the master report, select the SubReport item. In the Properties Window, go to the Events tab and double-click the ItemDataBound event to create a handler. Replace the handler with the code below that sets the SubReport (the Telerik.Reporting.Processing version of SubReport) to the "ShowEmployees" value. [C#] Setting the SubReport Visible Property private void subReport1_ItemDataBound(object sender, System.EventArgs e) { (sender as Telerik.Reporting.Processing.SubReport).Visible = (bool)this.ReportParameters["ShowEmployees"].Value; } [VB] Setting the SubReport Visible Property Private Sub subReport1_ItemDataBound(ByVal sender As Object, ByVal e As System.EventArgs) (TryCast(sender, Telerik.Reporting.Processing.SubReport)).Visible = DirectCast (Me.ReportParameters("ShowEmployees").Value, Boolean) End Sub 4. Click the Preview button to display the report. With the "ShowEmployee" set to True, the report shows master and detail records (and the column heading shows "Department/Employee"):
110
...with "ShowEmployees" set to False the report shows departments only. Notice the column heading displays "Department".
111
Summary
This section demonstrated how SubReports are used in situations where Master-detail, aggregate reports and where ever report data can't be included in a single report. We also looked at how to conditionally hide or show SubReports based on the value of an expression.
112
Objectives
This section explores the array of choices in Telerik Reporting for altering the appearance of your report using styles and style rules. You will learn how to define a style sheet, to export and to re-use the stylesheet in other reports.
Styling Basics
Telerik Reporting uses a built-in styling model that is similar to CSS. The model provides for very fine -grained visual customization of all elements of a report directly in the Visual Studio designer. This CSS-like mechanism offers full control over such things as the background, colors, borders, and images for every item on your report. You can assign styles by using CSS selectors that point to report items based on their type, the attributes of the item, a style name, or if the report item is a descendant of a given report item. Like CSS, styles can be defined globally, inherited from parent items and can also be explicitly defined for a report item. A child report item placed within anotherreport itemderives its styling based on the following precedence:
Lowest Priority -Parent: If the parent control has a style applied, the child inherits the parent's styling. Second Priority - Global: If any of the global styles apply to the child then the control will use this styling. Parent styling is ignored in this case. Highest Priority - Inline: If the childitem'sstyle properties have changed from their defaults,the child styleproperties are honored. Global styling and parent style are ignored in this case.
At design time you can use the styling mechanism without needing to understand much of the underlying mechanics.Right-click a report item to get the style related context menu options:
113
Style...: Displays the Edit Style dialog so that you can change the Text, BackGround, Edges and Line styles. Copy Style: Persists all the style information for a report item. Paste Style: Applies all the styling from one report item to another. This becomes enabled once the Copy Style menu option has been selected once. You can copy and paste styles between disparate items, e.g. copy the style from a TextBox and paste it to a section. Reset Style: Restores the style properties to the global style.
Or, you can also use the Style property of any report item to invoke the Edit Style dialog (using the ellipses), or edit each of the sub properties individually:
Style Rules
The styling mechanism goes deeper than the simple direct assign of style properties. Telerik Reporting offers a much more flexible, CSS-like, capability than the simple choices available in the Style property alone. Telerik Reporting can flexibly handle entire categories of report items by using Style Rules that determine what items a style is applied to.A Style Ruleisdefined using "Selectors" (i.e. criteria for applying a style): 1. TypeSelectorstarget all report items of a particular type (for example TextBox or DetailSection). 2. StyleSelectors are named styles that can be applied toreport items through thereport item'sStyleName property. 3. AttributeSelectors target allreport itemswith a particular attribute (for example Font Family= Verdana). 4. DescendantSelectors target report items which descend from (or, are placed within) other report items. For example you can define a style that should be applied to all TextBoxes in the report's DetailSection. Use the Report object's StyleSheet property to invoke the StyleRule Collection Editor. When you create a report using the Report Wizard, the wizard will pre-define several style rules. The screen shot below shows style rules defined for a simple listing report in the "Apex" style. Each StyleRule has a collection of Selectors and a Style property. The Selectors determine when the style should apply and the Style property defines the appearance of the selected item. In this example, all four rules have Selectors that use a named style as a criteria.
114
115
We can fix most these problems with the judicious use of styles and Style Rules. The key word here is "judicious" - if you go crazy with styles, you can still end up with with a visual mish-mash. A little restraint goes a long way. Also, keep in mind what you're trying toaccomplish here:
Provide visual cues to the reader as to where the title, column headers and content are within the page.They shouldn't have to think about it. Make the report readable. Background and text colors should contrast so the reader doesn't go blind. Of course, to make the report attractive. Here again, not overdoing loud or contrasting colors, heavy or ornate font styles and shapes for the sake of shapes, will make the report more usable on a day-to-day basis. Remember how web sites looked "back in the day", with large red fonts, broad beveled borders and the liberal use of blinking banners? Avoid that pattern and keep the report looking professional.
116
117
118
6. Click OK to close the TypeSelector Collection Editor dialog. 7. In the StyleRule Collection Editor, open the Style property. Select the BackColor sub-property and choose "Lavender" from the list of Web colors. 4. Create a style rule for the page footer section: 1. Click the Add button to create a StyleRule. 2. Click the Selectors property ellipses. This will display the TypeSelector Collection Editor dialog. 3. Click the Add button drop down arrow and choose TypeSelector. 4. Click the Type property ellipses. This will display the Select Type dialog. 5. Select the PageFooterSection type and click OK to close the Select Type dialog. 6. Click OK to close the TypeSelector Collection Editor dialog. 7. In the StyleRule Collection Editor, open the Style property. Select the BackColor sub-property and choose "Lavender" from the list of Web colors. 8. Click OK to close the StyleRule Collection Editor and see your changes in the designer.
119
5. Create a style rule for the page title: 1. In the Properties Window, click the ellipses of the StyleSheet property to display the StyleRule collection editor. 2. Again, use the report StyleSheet property to open the StyleRuleCollection Editor. 3. Click the Add button to create a StyleRule. 4. Click the Selectors property ellipses. This will display the TypeSelector Collection Editor dialog. 5. Click the Add button drop down arrow and choose StyleSelector. 6. Set the StyleName property to "PageTitle". 7. Click OK to close the TypeSelector Collection Editor dialog. 8. In the StyleRule Collection Editor, open the Style property. Set the Font.Size sub-property to 15pt. 9. Click OK to close the StyleRule Collection Editor. Your changes will not be visible yet. 10. Select the TextBox item from the upper left corner (it should read "Product Reviews"). 11. Set the StyleName property to "PageTitle". Your changes should take effect. 6. Create a style rule for the column headings: 1. In the Properties Window, click the ellipses of the StyleSheet property to display the StyleRule collection editor. 2. Again, use the report StyleSheet property to open the StyleRuleCollection Editor. 3. Click the Add button to create a StyleRule. 4. Click the Selectors property ellipses. This will display the TypeSelector Collection Editor dialog. 5. Click the Add button drop down arrow and choose StyleSelector. 6. Set the StyleName property to "ColumnHeadings". 7. Click OK to close the TypeSelector Collection Editor dialog. 8. In the StyleRule Collection Editor, open the Style property. Set the Font.Bold sub-property to true. The StyleRule Collection Editor should at this point look like the screenshot below:
120
9. Click OK to close the StyleRule Collection Editor. Your changes will not be visible yet. 10. Select all three column heading TextBox items (hint: hold down the Control key and click each of the TextBox items with the mouse). 11. Set the StyleName property to "ColumnHeadings". Your changes should take effect. 7. The designer should look something like the example below:
121
122
Exporting
Take the previous "Adding Style Rules" example as a starting point: 1. Click the report StyleSheet property ellipses. 2. Click the Export button. 3. Provide a file name and click the Save button.
Importing
1. Click the ExternalStyles property ellipses. This will display a File Collection Editor dialog. 2. Click the Add button (found in the upper right of the dialog) to display the Open dialog. Note: you can add multiple style files to your report. 3. Select an XML file that contains previously exported styles and click the Open button.
123
4. Click OK to close the File Collection Editor and see the styles applied.
124
[C#] Adding a StyleRule //Create a StyleRule Telerik.Reporting.Drawing.StyleRule myStyleRule = new Telerik.Reporting.Drawing.StyleRule(); //Add a TypeSelector myStyleRule.Selectors.Add( new Telerik.Reporting.Drawing.TypeSelector( typeof(Telerik.Reporting.DetailSection))); //Add formatting myStyleRule.Style.BackgroundColor = System.Drawing.Color.WhiteSmoke; myStyleRule.Style.Color = System.Drawing.Color.DodgerBlue; //Add rule to Style Sheet this.StyleSheet.Add(myStyleRule); [VB] Adding a StyleRule 'Create a StyleRule Dim myStyleRule As New Telerik.Reporting.Drawing.StyleRule() 'Add a TypeSelector myStyleRule.Selectors.Add(New Telerik.Reporting.Drawing.TypeSelector(GetType (Telerik.Reporting.DetailSection))) 'Add formatting myStyleRule.Style.BackgroundColor = System.Drawing.Color.WhiteSmoke myStyleRule.Style.Color = System.Drawing.Color.DodgerBlue 'Add rule to Style Sheet Me.StyleSheet.Add(myStyleRule)
Summary
In this section you learned how to work with styles, how to create style rules, how to export stylesheets and how to re-use stylesheets in other reports.
125
Objectives
This section demonstrates how to perform common useful tasks such as displaying alternating row colors andhighlighting report items based ondata conditions using conditional formatting.
In this situation we only want to format the TextBox report item that contains the credit card type. You can select the TextBox in the designer and use the ConditionalFormatting property to invoke the Conditional Formatting Rules... dialog. From there you can define formatting rules that describe the condition that triggers formatting and the format itself. The example below shows formatting that is triggered when
126
Filters are made up of one or more filter conditions. Each filter condition is made up of an Expression, Operator and Value.When all filter conditions are met, the rule is fired and the style is applied. To style the report section or report item, click the Style... button to invoke the Style Builder dialog. Here you can change the Text, Background, Edges and Line Style.
127
Formatting Rows
You can format the entire row by setting the ConditionalFormatting property of the detail section. There you can check the value of any bound data column and set the format based on the data. Using the credit card list example, we can "gray-out" rows where the credit card has expired.
128
3. Select the detail section of the report. 4. In the Properties Window, locate the ConditionalFormatting property and click the ellipses. This step will invoke the Conditional Formatting Rules... dialog. 5. Click the New Rule... button. This step will invoke the Edit Formatting Rule dialog. 6. Click the New button to create a new condition and format. 7. In the Expression column enter the expression below. The expression creates a date suitable for comparing with a system date. The date is created from the year and monthfound in the credit card table: =CDate(CStr(Fields.ExpMonth) + "/" + "01" + "/" + Cstr(Fields.ExpYear)) 8. In the Operator column select "<" from the drop down list. 9. In the Value column enter the expression "= Now()". 10. Click the Style button. This step will invoke the Style Builder dialog. 11. Click Text from the liston the left side of the Style Builder dialog. Select "GrayText" from the Color drop down list.
129
12. Click OK to close the Style Builder dialog. 13. Click OK to close the Edit Formatting Rule... dialog. 14. Click OK to close the Conditional Formatting Rules dialog. 15. Click the Preview tab to see the report. Depending on the current value of "Now()", you may not be seeing enough contrast in the data (in other words, all the dates are expired). Instead of "Now()" you can use another expression with a hard-coded date for this exercise, e.g."= CDate("1/1/2008")"
130
1. Select the detail section of your report. 2. Select the ConditionalFormatting property of the detail section. 3. Click the New Rule button. 4. Enter the expression "= RowNumber()%2" 5. Select the equal "=" operator from the drop down list. 6. Enter the value as "=1". 7. Click the Style button. 8. Click the Background style item. 9. Enter the color as "#CAFFCA". 10. Click OK to close each of the open dialogs. 11. Click the Preview tab to view the report.
131
[C#] Define and Apply Conditional Formatting Rules // Note: this example requires the Telerik.Reporting.Data namespace reference // Define an alternating row style FormattingRule alternateRowsRule = new FormattingRule(); // Define the rule to trigger the format alternateRowsRule.Filters.Add( new Filter("= RowNumber()%2", FilterOperator.Equal, "=1")); // Define the style to be applied when rule is true alternateRowsRule.Style.BackgroundColor = Color.FromArgb(204, 255, 204); // Add the rule to the ConditionalFormatting collection this.detail.ConditionalFormatting.Add(alternateRowsRule); [VB] Define and Apply Conditional Formatting Rules ' Note: this example requires the Telerik.Reporting.Data namespace reference ' Define an alternating row style Dim alternateRowsRule As New FormattingRule() ' Define the rule to trigger the format alternateRowsRule.Filters.Add(New Filter("= RowNumber()%2", FilterOperator.Equal, "=1")) ' Define the style to be applied when rule is true alternateRowsRule.Style.BackgroundColor = Color.FromArgb(204, 255, 204) ' Add the rule to the ConditionalFormatting collection Me.detail.ConditionalFormatting.Add(alternateRowsRule)
Summary
In this section you learnedhow to apply conditional formatting to react to different kinds of data and to perform common tasks like alternating row colors.
132
Objectives
Learn to create a report section using code only. Learn to create a report item using code only. Create TextBox, Shape and PictureBox report items at run-time.
Creating Sections
To get started, create a new report class and cancel the Report Wizard. You should have three empty report sections, i.e. page header, detail and page footer.If you look at the generated code found in "Report1.Designer.cs" in theregion titled "Component Designer Generated Code"for the detail section you see: [C#] Generated Detail Section Code this.detail = new Telerik.Reporting.DetailSection(); //. . . this.detail.Height = new Telerik.Reporting.Drawing.Unit(0.21045596897602081, ((Telerik.Reporting.Drawing.UnitType)(Telerik.Reporting.Drawing.UnitType.Inch))); this.detail.Name = "detail"; [VB] Generated Detail Section Code Me.detail = New Telerik.Reporting.DetailSection() '. . . Me.detail.Height = New Telerik.Reporting.Drawing.Unit(0.210455968976021, (DirectCast ((Telerik.Reporting.Drawing.UnitType.Inch), Telerik.Reporting.Drawing.UnitType))) Me.detail.Name = "detail" In this same way you can create new sections for all portions of the report.Here are theobjects that encapsulate the functionality of each type of section:DetailSection, GroupHeaderSection, GroupFooterSection, PageHeaderSection, PageFooterSection, ReportHeader and ReportFooterSection. The general pattern is that the section is created, assigned to the appropriate section property of the report and the section properties are defined.
133
Create the TextBox Instance Assign the Value property Place the TextBox somewhere on the report Add the TextBox to a report section
For example:
134
Shape
Shape report items come with a number of predefined primitive elements that can help you build visual design features of your report. Here is a sample of some of the basic shapes and how they can be styled:
135
Creating a Shape report item is similar to the TextBox except that you must assign a ShapeType instead of a Value. ShapeType takes an instance of one of the many ShapeBase descendents. In the designer you get a visual clue from the ShapeType property drop down list.
When coding you can get a list of the available ShapeTypes using Intellisense against the Telerik.Reporting.Drawing.Shapes namespace, with the naming convention "<a shape name>Shape".
136
Here is the minimal code that creates an elliptical shape in the detail section of the report. [C#] Minimal Code for Creating a Shape // Create a new ellipse shape Shape shape = new Shape(); // Set a specific ShapeType shape.ShapeType = new EllipseShape(); // Handle size and dimensions shape.Dock = DockStyle.Fill; // Assign the shape to the report section this.detail.Items.Add(shape); [VB] Minimal Code for Creating a Shape ' Create a new ellipse shape Dim shape As New Shape() ' Set a specific ShapeType shape.ShapeType = New EllipseShape() ' Handle size and dimensions shape.Dock = DockStyle.Fill ' Assign the shape to the report section Me.detail.Items.Add(shape)
PictureBox
You can include images to your reports using the PictureBox report item. The critical properties here are:
Value: Create an Image object and assign to this property Sizing: This adjusts how the image fits to the PictureBox, if the PictureBox fits to the image, and if any clipping should occur
The example below assigns a standard .NET framework Bitmap object to the PictureBox Value property. The image itself is the Telerik Reporting logo, taken from a Telerik web site page and added to the project.
137
[C#] Minimal Code for Creating a PictureBox // provide enough room in the header to contain the full image this.pageHeader.Height = new Unit(1, UnitType.Inch); // create an instance of the PictureBox Telerik.Reporting.PictureBox pictureBox = new Telerik.Reporting.PictureBox(); // assign a Bitmap object to the Value property pictureBox.Value = new Bitmap("productLogo.gif"); // use AutoSize so that report item fits the image pictureBox.Sizing = ImageSizeMode.AutoSize; // add the report item to the page header section this.pageHeader.Items.Add(pictureBox); [VB] Minimal Code for Creating a PictureBox ' provide enough room in the header to contain the full image Me.pageHeader.Height = New Unit(1, UnitType.Inch) ' create an instance of the PictureBox Dim pictureBox As New Telerik.Reporting.PictureBox() ' assign a Bitmap object to the Value property pictureBox.Value = New Bitmap("productLogo.gif") ' use AutoSize so that report item fits the image pictureBox.Sizing = ImageSizeMode.AutoSize ' add the report item to the page header section Me.pageHeader.Items.Add(pictureBox) At design time you use the Value property to specify the PictureBox image data. The Value property is a System.Object and accepts only 2 specific types:
System.String - interpreted as an item binding expression that should evaluate to System.Drawing.Image or byte[]. The Image or byte arrayis used internally as Image data. System.Drawing.Image - the Image to be rendered.
To use static images (not from the data source) you can apply any standard NET Framework approach to load them:
System.Drawing.Image.FromFile() loads an image from a file System.Drawing.Image.FromStream loads animage from a data stream System.Resources.ResourceManager lets you work with embedded resources System.Drawing.Bitmap(Type, string) constructor loads an image from a resource
138
139
1. To get this effect, start with the previous "Create a Section" project and make these changes: 2. Add Telerik.Reporting.Drawing.Shapes to your "using" (C#) or "Imports" (VB)portion of the code. 3. Add code below to create the new report items to your report class constructor, just below the section header creation code. The code example will show the entire report class constructor. Look for the comments that indicate the start and end of the new code to be added: [C#] Create Shapes and TextBoxes public Report1() { InitializeComponent(); // Define header section, set dimensions/appearance, and add to report ReportHeaderSection headerSection = new ReportHeaderSection(); headerSection.Height = new Telerik.Reporting.Drawing.Unit(1, UnitType.Inch); headerSection.Style.BackgroundColor = Color.LightSteelBlue; headerSection.Style.BorderStyle.Default = BorderType.Ridge; this.Items.Add(headerSection); // --- Start new code --// Unit size used for both height and width Unit shapeSize = new Unit(.75, UnitType.Inch); // variable to track left-to-right placement of circle shapes double currentX = .5; // variable to track transparency of circle shapes int currentAlpha = 20; // controls the number of iterations when creating circle shapes const int numberOfCircles = 3; // amount to increment horizontal placement of circle shapes const double addToX = .2; // amount to increment alpha const int addToAlpha = 25; // create a series of circles behind the text for (int i = 0; i < numberOfCircles; i++) { // create a new ellipse shape and set the dimensions Shape shape = new Shape(); shape.ShapeType = new EllipseShape(); shape.Height = shapeSize;
140
141
Summary
In thislesson you learned how to create report sections and items at run-time. You also became familiar with the specifics of theTextBox, Shape and PictureBox report items.
142
Objectives
In this section you will also be introduced to the report life cycle - a critical part of understanding how data is made available, at what times data is available and in what sections of the report. The report, section and item events will be shown and then put in the context of the report life cycle. Finally, you will create an event handler for the report detail section that uses data from multiple columns to format a single column.
Page Headers and Footers: Item binding expressions cannot use data fields or aggregate functions. Paging is specific to rendering format and must occur during rendering, well after early report processing where data binding occurs. PageNumber and PageCount global objects are available only in this section. Report Headers, Footers and Groups: For these sections, only aggregate functions should be used in expressions. If an expression specifies a data field without an aggregate, the First() aggregate function is used by default. TheFirst() function returns the first record of the data source for the specified field. Detail Section: The detail section can contain data bound fields and any function available in the edit Expression dialogexcept PageCount and PageNumber.
143
Binds the Report Definition with data from the report data source. Performs all grouping, sorting and filtering calculations. Evaluates all Expressions except page header and footer section items. Fires itemBinding and Bound events. Produces a Report Instance. Report instances may be stored and rendered at a later time.
The Report Instance is passed to a specific rendering extension (e.g. MHTML orPDFoutput formats). The report instance is paged if the output format supports paging. Item expressions are evaluated in the page header and footer sections for every page. The report is rendered to the Output Document.
Rendering
Telerik reports can be rendered to a number of output formats.Each format has characteristics that determine usage and may impose certain limitations. For example, a report rendered as HTML you can expect to have a dynamic, HTML table-basedarrangement while a PDF report will have an exact set of dimensions. Each output format is produced by a rendering extension. You can break these rendering extensions out into a few general categories:
Data: CSV
144
Logical page layout: HTML, Excel Physical page layout: Image, PDF
See the online help under "Design Considerations for..." for more detail involving extension specific rendering, pagination andpotential limitations. Also be aware that page setup options can also alter report appearance at design-time, run-time or when the user changes the options prior to printing. Page setup options are controlled by the PageSettings property and apply to all report output types.
Landscape or Portrait paper orientation. Margin sizes. Paper Kind: This option includes standard paper size configurations e.g. legal, envelopes, labels. Paper Size: If the PaperKind property is "Custom", then the PaperSize Width and Height properties can be set to whatever dimensions suit your purpose.
145
The SubReport item, like the Report,also has a NeedDataSource that fires when the subreport is not data bound. Here isa simple example that shows a situation where you might choose an ItemDataBound event over an expression. Even in this situation you could use expressions to get the same effect. Depending on your infrastructure and in-house standards, you may prefer to perform some tasks using code. In this example we handle the ItemdataBound event for a TextBox that contains a status number. We have an enumeration defined that maps the numbers to meaningful status descriptions.
In the code we use the "sender" as the reference to the TextBox, get the status number and convert it to the enumeration's string representation. [C#] Handling the ItemDataBound Event enum Status { Pending = 1, Approved = 2, Rejected = 3, Complete = 4 } ; private void statusDataTextBox_ItemDataBound(object sender, System.EventArgs e) { Telerik.Reporting.Processing.TextBox txtStatus = (Telerik.Reporting.Processing.TextBox) sender; txtStatus.Text = ((Status)Convert.ToInt16(txtStatus.Text)).ToString(); } [VB] Handling the ItemDataBound Event Enum Status Pending = 1 Approved = 2 Rejected = 3 Complete = 4 End Enum Private Sub statusDataTextBox_ItemDataBound(ByVal sender As Object, ByVal e As System.EventArgs) Dim txtStatus As Telerik.Reporting.Processing.TextBox = DirectCast(sender, Telerik.Reporting.Processing.TextBox) txtStatus.Text = (DirectCast(Convert.ToInt16(txtStatus.Text), Status)).ToString()
146
Report Definition
The Report Definition is created during the first stage of the life cycle. This is the actual .NET class that represents the report. It is always a subclass of Telerik.Reporting.Report and contains information about report items and their properties. Report items are represented by the private fields of the report class. For example, if you add a TextBox to the Detail Section of the report in the designer, a private field of type TextBox is automatically added to the generated code-behind. This object will later serve as thedefinition for creating a concrete instance of the TextBox for each row in the data source. Items defined in this phase of the life cycle, i.e. "definition items", are from the Telerik.Reporting namespace.
Report Processing
The second stage of the report life cycle involves combining the report definition with the data source. The processing engine:
Performs all grouping, sorting and filtering calculations Iterates over all rows from the data source Creates the appropriate processing items based on the itemdefinitions created earlier and the actual data.
Objects produced in this phase of the life cycle are called"processing items" andare from the Telerik.Reporting.Processing namespace. Based on the original item definition (Telerik.Reporting.TextBox for example) and the actual data in the current data row a new item is created.A processing item (Telerik.Reporting.Processing.TextBox for example) bears all characteristics of itsdefinition item, but is bound to the respective data field from the current data row. For example, thedefinition TextBox Value property may contain something like =Fields.FirstName,but the processing item Text property will be equal to John. Data Binding During Processing Just before the processing item is bound to data, the ItemDataBinding event of itsdefinition item is raised. Then the processing item is bound to data and finallythe ItemDataBound event is raised. Suppose that we have a TextBox containing employee job positions.Assume that the TextBox Value property is =Fields.JobPosition, where "JobPosition" is a column from the data source containing values like Team Leader, Senior Developer, Quality Assurance, etc. For the sake of example, let's further suppose that we want to highlight the developers column text in a blue color. First we need to attach to the TextBox ItemDataBound event. The sender parameter of the event handler method is in fact the processing report item and has already been data bound. Its Text property will hold the job position of the current employee. The event handler will be called for each data row, i.e. for each employee we have in the data source. In this example, if Text contains "Developer", then the TextBox Style property is used to color the background a blue color. [C#] Handling the ItemDataBound Event private void textBox1_ItemDataBound(object sender, EventArgs e) { Telerik.Reporting.Processing.TextBox txtPosition =
147
Report Rendering
After processing is over, the processed report is ready for rendering in one of the many available formats.
148
149
18. In the report designer, select the detail section with the mouse. In the Property Window, click the events button ( ). Double click the ItemDataboundEvent to create an event handler. 19. Replace the event handler code with the code below. [C#] Handling the Detail Section ItemDataBound Event private void detail_ItemDataBound(object sender, System.EventArgs e) { // Get the detail section object from sender Processing.DetailSection section = (Processing.DetailSection)sender; // From the section object get the DataRowView DataRowView dataRowView = (DataRowView)section.DataItem; // Also from the section object get the items in the report Processing.ReportItemBase[] items = (Processing.ReportItemBase[])section.Items.Find("shapeReorder", false); /// Get the specific report item you want to change, /// use the dataRowView to get the underlying data, /// then change the report item properties based on the data. if (items.Length > 0) { Processing.Shape shape = items[0] as Processing.Shape; int quantity = Convert.ToInt16( dataRowView["Quantity"]); int reorderPoint = Convert.ToInt16( dataRowView["ReorderPoint"]); bool timeToReorder = quantity < reorderPoint * .5; shape.Style.BackgroundColor = timeToReorder ? Color.Red : Color.White;
150
Remember that the reporting runtime object model is different from the design-time model. You should use the Telerik.Reporting.Processing namespace objects within event handlers.
Summary
In this section of the tutorial you became familiar with the basic report life cycle. Using your knowledge of the life cycle, you know when data bound fields can be used in contrast with global objects such as PageNumber orPageCount. You have also learned how to handle report, report item and section level events.
151
Objectives
This section will show you how to print sheets of labels from a datasource, how to print data that displays in multiple columns, and how to create reports that display in custom paper dimensions.
152
4. Create a new DataSource for the project using the SQL below: [SQL] List Products SELECT Production.Product.NAME AS Product, Production.ProductPhoto.ThumbNailPhoto, Production.Product.ProductNumber,Production.Product.ListPrice, Production.Product.StandardCost FROM Production.Product INNER JOIN Production.ProductProductPhoto ON Production.Product.ProductID = Production.ProductProductPhoto.ProductID INNER JOIN Production.ProductPhoto ON Production.ProductProductPhoto.ProductPhotoID = Production.ProductPhoto.ProductPhotoID 5. Using the Data Explorer, add the fields to the editable area of the Detail section. You may also want to add TextBox controls to act as labels. Place the "ThumbNailPhoto" at the bottom of the column:
153
154
Lab: Labels
Telerik Reports supports an enormous range of label types and size layouts. The Report Wizard includes a Labels option that helps guide you through the process of locating, choosing and configuring the right layout for your purposes. 1. Using the Report Wizard, create a new Report based off the SQL below: [SQL] Address Listing SELECT TOP (30) Person.Contact.FirstName, Person.Contact.LastName, Person.Address.AddressLine1, Person.Address.AddressLine2, Person.Address.City, Person.StateProvince.StateProvinceCode AS State, Person.Address.PostalCode FROM Person.Address INNER JOIN Sales.SalesOrderHeader ON Person.Address.AddressID = Sales.SalesOrderHeader.ShipToAddressID INNER JOIN Person.Contact ON Sales.SalesOrderHeader.ContactID = Person.Contact.ContactID
155
5. In the Customize Label Settings page, set the Top margin to ".5" and tab off theentry field to see the change in the preview area. Because of the WYSIWYG nature of Telerik Reporting, you can actually measure the sheet of paper to get the margins. For instance, if you measure a half an inch from the edge of the paper to the first label, you can enter that amount as the top margin here. You can use any of the measurement systems: mm, cm, in, px, pt, pc.
156
It needs a little help because the fields are all equal sized and not formatted appropriately for address labels. 7. Delete the TextBoxes "=Fields.LastName", "=Fields.State" and "=Fields.PostalCode". 8. Rearrange the TextBox controls so that each one appears on a line as shown in the screenshot below.
157
The real proof isin the printing. When you print on actual, not virtual label sheets, the Customize Label Settings page of the wizard is invaluablefor adapting to your physical printing setup.
Summary
In this section you learned how to print labels from a database of addresses, how to display data in multiple columns and how to create reports in any size configuration.
158
Objectives
In this section you will become familiar with two Telerik Reporting controls for viewing your reports within Windows and Web applications. You will also export your reports programmatically by rendering a report to a stream of bytes that can be written to various file formats on disk, including image and PDF.
159
The toolbar for both viewersallows the user to interact with the currently-loaded report:
Stop loading (useful when a large report is taking a long time to load) Refresh Go to first page Go to preview page Go to a specific page Total number of pages Go to next page Go to last page Print Export: Reports can be exported to Web Archive(MSHTML), TIFF, PDF, RTF, Exceland comma delimited files. Select a format, then click the Export button. Zoom level
Set the Report property of the viewer using the drop down list in the Properties Window.Be sure to reference the assembly containing the report so that the report shows up in the drop down. Also be sure to build the application so that reports show up in the drop down list. To size the report contents to the ReportViewer window use the ZoomMode property.ZoomMode can be
160
To tailor the controls available in the ReportViewer, set the boolean properties ShowExportButton, ShowPageNavigationControls, ShowPageSetup, ShowParametersButton, ShowPrintButton, ShowProgress, ShowRefreshButton, ShowZoom. The CurrentPage property defaults to zero but can be used to start at another page in the report.
ProgressText: The text that displays in the viewer while the report is being generated. The default is "Generating report...". Skin: Select from one of the predefined skins (see screenshot below).
Exporting to PDF
For example, you canexport directly to a PDF file and have it created right on local disk: 1. Open one of the previous solutions that contains a defined report, such as the "Adding Style Rules" project. 2. In the Solution Explorer, right-click the solution and select Add | New Project from the context menu. 3. Select Windows Application, provide a unique project name and click OK. 4. Also in the Solution Explorer, right click the References node and Add Reference... 5. Add a reference to Telerik.Reporting and Telerik.Reporting.Processing. You can use the Browse tab of the Add Assembly dialog to find these assemblies in your Telerik Reporting installation directory under the \Bin folder. 6. Also add a reference to the assembly that contains your report class. Use the Projects tab to list the other assemblies in your solution. 7. Add a button to the default form. 8. Double-click the button to create a Click event handler. Add the code below to the event handler.
161
Exporting to Image
Now try swapping out the button click event handler code with the code below. You will need to add a System.Collections reference to support the Hashtable. Also, change the reference to MyReport to use the name of the report class you referenced. This example has a similar setup to the previous example, but the returned array of bytes is handled differently. The bytes are plugged into a MemoryStream constructor and the stream is used as a parameter to
162
Emailing a Report
163
164
165
Build the application. Set the Telerik Reporting assembly references Copy Local flag to True. Copy the contents of the bin directory to the server. Run the application.
Not covered here, but important considerations when deploying reports in a production setting are...
Database client configuration and connectivity Permissions on the deployment server. The permissions and authentication for the deployment server will vary widely according to operating system, configuration and the type of application deployed (web vs. Windows).
The example below takes a bare-bones report with no database connectivity or other dependencies and displays it in a simple Windows viewer application. This example requires a separate server machine to copy the application files to. Deployment does NOT require:
Any of the design-timeassemblies includingTelerik.Reporting.Design.dll, Telerik.Reporting.VsPackage.dll, Telerik.ReportViewer.Design.dll Assemblies involved in conversion from other reporting platforms. These assemblies are also only used at design time and may include Interop.CRAXDRT.dll, Telerik.ReportConverter.ActiveReports3.dll, Telerik. ReportConverter.CrystalReports11.dll, Telerik.ReportConverter.XtraReports7.dll.
166
167
13. Test run the application from the server. For more detail on deploying Telerik Reporting on a server seehttp://www.telerik.com/help/reporting/install_DeployingOnAServer.html.
Summary
In this section you worked with the Windows and Web report viewer controls. You also programmatically rendered your report as an image and PDF. Finally, you learned how to render your PDF directly to a browser.
168
169