Creating your First Crystal Report for Use in a .NET Application
 
Published: 16 Mar 2010
Abstract
Have you ever had to create a custom report within an application you have written for a customer? Most developers have, and there are two schools of thought on how developers normally perform this task. Some choose to create the report using the same technology that the application was created in (ASP, WinFrom, WPF) while others choose to use a reporting package such as Crystal Reports. Using a reporting package will help create reports rapidly. This article walk you through the creation of your first report using Crystal Reports.
by Jeff McWherter
Feedback
Average Rating: 
Views (Total / Last 10 Days): 48129/ 148

Introduction

Reports are a mere after thought on many projects. A great deal of effort is put into creating forms to manipulate the customer’s data, but many developers and project managers wait until the last minute to create reports. At this point in many projects, the budget is nearly gone, and project stakeholders are looking for something that may not be delivererable within the current budget constraints.  When the time comes, that a customer asks for a great deal of data to be formatted in a specific way, with multiple search criteria selected, developers are often times left scrambling to develop a solution to fit within their budget.

Depending upon the complexity of the data to be rendered, some developers decide to present the data to their users using the same technologies that their application was create created with (ASP, Win Forms, WPF, etc.) instead of a reporting package such as Crystal Reports. Many believe because that budget constraints mean that they do not have time to learn a new tool or purchase reporting tools. In simple situations, this option may be viable, but when your reports start to become more complex, using libraries that are created specifically for report writing will make life much easier. This is where Crystal Reports comes in.

Crystal Report Files

Let us first begin by discussing report files. Each reporting package handles the report files slightly differently, but underlying concepts are the same. With Crystal Reports, the report files are .RPT files. The .RPT files are created using the Crystal Reports Designer, which is available as a stand-alone program, or an add-in to Visual Studio. Many versions of Visual Studio ship with a version of the Crystal Reports designer add-in, meaning you can create Crystal Reports within Visual Studio without having to buy additional software or licenses. The Crystal Reports Designer add-In for Visual Studio is a good tool, but the stand-alone Crystal Reports designer has additional features that make report creation much easier. Examples in this article will use the stand-alone Crystal Reports designer, but all of the features discussed are available in the Visual Studio add-in as well. 

A basic Crystal Report file is divided into five sections.

Report Header

The Report Header is only rendered once per report, on the top of the report. It is common for developers to place information such as company logos and filter criteria specific to the report in this section.

Page Header

The Page Header is rendered on the top of each page of the report. On the very first page of the report, the Page Header is rendered under the Report Header. It is common for developers to place field names of the columns that are rendered on the report in this section.

Details

The details section of a report is where the magic happens. An instance of the details section is rendered for each record in the data set that was passed to the Crystal Report file. Developers place the columns of data that needs to be presented on the report in this section.

Report Footer

The Report Footer displays only once on the last page of the report.

Page Footer

The Page Footer is rendered at the bottom of each page of the report. In this section it is common to see developers place page numbers and the date/time that the report was printed.

Figure 1:  Report Sections

Data Schema

After you have created the Crystal Report file, the next step is defining a data schema. After you have “informed” the Crystal Report file of the data schema, a list of fields obtained from the data schema, will appear in the field explorer. Once the fields appear in the field explorer, you can "drag" the field to the report.

Before we discuss how to "inform" the Crystal Report of the data schema, let us first discuss how to obtain the data schema.  Creating an XML data schema is as simple as calling the WriteXMLSchema method off of a DataSet Object within code (VB or C#). The code below is a working example of calling a method to retrieve a list of employees, converting the list of employees into a DataSet object, and then writing the XML schema to a file named EmployeeData.xml.

Listing 1

List<Employee> employees = GetEmployeesAsList();
DataSet employeeDataSet = ListToDataset<Employee>(employees);
employeeDataSet.WriteXmlSchema(@"C:\EmployeeData.xml");

Below is what the EmployeeData.xml contains.  You will notice each field is listed with the data type.

Listing 2

<?xml version="1.0" standalone="yes"?>
<xs:schema id="ArrayOfEmployee" xmlns="" 
 xmlns:xs="http://www.w3.org/2001/XMLSchema" 
 xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="ArrayOfEmployee" msdata:IsDataSet="true" 
   msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Employee">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="FirstName" type="xs:string" minOccurs="0" />
              <xs:element name="LastName" type="xs:string" minOccurs="0" />
              <xs:element name="Address" type="xs:string" minOccurs="0" />
              <xs:element name="City" type="xs:string" minOccurs="0" />
              <xs:element name="State" type="xs:string" minOccurs="0" />
              <xs:element name="PostalCode" type="xs:string" minOccurs="0" />
              <xs:element name="Role" type="xs:string" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

To "inform" the Crystal Reports file of the data schema, click on the Database Expert option in the toolbar, click Create New Connection and select ADO.NET (XML) as shown in Figure 2, and select the data schema that was just generated.

Figure 2:  Setting the data connection to the report

Once your data schema has been defined, you should see a list of columns in the Field Explorer under Database Fields as shown in Figure 3.

Figure 3:  Crystal Reports field expert

 

You can now “drag” your fields onto to your report.

Crystal Reports Viewer

Now that the Crystal Reports file has been created, you need to display the report in your project. For our example, we will be using the Crystal Reports ASP.NET controls. The methods outlined here are very similar to the Win Forms controls as well.

To view your newly created Crystal Report file in your custom application, you will need to use the Crystal Report Viewer control as shown in the code below.

Listing 3

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
 Inherits="ObjectModel._Default"%>
 
<%@ Register Assembly="CrystalDecisions.Web, Version=12.0.2000.0, Culture=neutral, 
 PublicKeyToken=692fbea5521e1304" 
 Namespace="CrystalDecisions.Web" TagPrefix="CR"%>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head> 
<body>
    <div id="reportMain">
        <asp:Label ID="lblError" CssClass="Error" runat="server" />
        <CR:CrystalReportViewer ID="crvMain" runat="server" />
    </div>
</html>

Now that the control is on the page, we need to “inform” the Crystal Reports Viewer control of the Crystal Reports file. We can do this in the code behind with the code that follows.

Listing 4

ReportDocument employeesReport = new ReportDocument();               
crvMain.ReportSource = employeesReport; 

After this step has been completed, we need set the data for the Crystal Report file that was loaded in the viewer. We simply use the SetDataSource method on the ReportDocument object.

Listing 5

ReportDocument employeesReport = new ReportDocument();
employeesReport.Load(@"\Employees.rpt");
employeesReport.SetDataSource(employees);         
crvMain.ReportSource = employeesReport; 

When all is said and done, you should have some type of method that looks similar to the LoadReport method below.

Listing 6

private void LoadReport()
{
List<Employee> employees = GetEmployeesAsList();
DataSet employeeDataSet = ListToDataset<Employee>(employees);
ReportDocument employeesReport = new ReportDocument();
 
      try
      {
            employeesReport.Load(@"Reports\Employees.rpt");
          employeesReport.SetDataSource(employees);
                
          crvMain.ReportSource = employeesReport; 
      }
      catch (Exception ex)
      {
lblError.Text = string.Format
 ("A system error has occurred while loading the report {0}", ex.Message);
      }
      finally
      {
            employeesReport = null;
      }
}

If you have followed all the steps above, you should now have your Crystal Report rendering in your custom application.

Beginner Tips

The first half of this article discussed creating a Crystal Report file, including it in your custom .NET application and then getting data to the report. The steps to accomplish this are not the complicated, but the report that we are rendering is not that complex either. The great thing about using a reporting package is the ability to adapt as reporting needs become more complex. Clients will often nit-pick every detail on reports.

Crystal Reports Processing

One of the most common complains about Crystal Reports is that reports take a long time to render. The team that created Crystal Reports has spent a great deal of time in recent versions correcting the performance issues. That being said, keeping the processing that Crystal Reports performs on the data to a minimum is still a wise course of action.

For example, Crystal Reports includes functionality to order records by fields. It is still better to order your data before it gets to the Crystal Report, since your database server will be able to perform this action much more quickly than Crystal Reports will.

Exporting

One of the most powerful features in Crystal Reports is the ability for your users to export your Crystal Report to over 14 other formats.

Crystal Reports RPT

HTML 3.2

HTML 4.0

Microsoft Excel (93-2007)

Microsoft Excel Data-Only (93-2007)

Microsoft Word (93-2007)

Microsoft Word Editable (93-2007)

PDF

Record Style-Columns with spaces

Record Style-Columns without spaces

Rich Text Format (RTF)

Separated Values (CSV)

Tab Separated Text (TTX)

Text

XML

It is beneficial to have the ability to export to all these different formats, but the export feature in Crystal Reports does not export each format in exactly the same way. This primarily comes from the way that the developer created the report, and also which format the report is being exported to. If you decide to allow your users to export your Crystal Report, I suggest you officially support the export to PDF (they always look exactly like the RPT file that was generated) and inform the users that the other exports may render the report a bit differently.

This is not to say that a report can’t be “tweaked” to work with all of the different export options, but it can be cumbersome to do so.

Grouping

One of the most commonly used features when creating a report is grouping similar data together. This is one of the biggest advantages of using a reporting package such as Crystal Reports. The example in Figure 4 shows the employee data used in other examples grouped by city.

Figure 4: Report grouped by city

 

To group similar data in Crystal Reports, use the “group” option, which can be found under insert>group in the Crystal Reports stand alone editor.

Figure 5: The group menu

You will then be prompted for which fields you would like to group by. For our example, we will just be grouping by the city field and not worrying about any other options.

Figure 6: Selecting a field to group the report on

After the group has been created, your report now contains two more sections: Group Header #1 and Group Footer #2. This allows you to place data specific to the group in these sections. It is common to place the field that is being group in the group header.

Conclusion

Creating custom reports for your .NET applications does not have to be difficult or time consuming. The goal of this article was to show how easy it is to create reports using Crystal Reports. Although the examples in this article are basic, Crystal Reports can be used to create very complex and advanced reporting suites to fit the need of almost all industries.  It’s a proven fact that managers love reports, so if you are looking for a way to get into their good graces, creating a well thought-out reporting suite may just get you that promotion that you have been looking for.



User Comments

Title: Many thanks   
Name: binam
Date: 2010-10-19 3:29:41 AM
Comment:
Many Many thanks for this article .
Title: A Look at Crystal Reports   
Name: Tahir Yaqoob
Date: 2010-10-11 6:35:28 AM
Comment:
A very nice article for any beginner to crystal reports.... thank's baby!!!!!!
Title: Article   
Name: Shawpnendu
Date: 2010-05-10 8:51:42 AM
Comment:
Very nice for novice developers.
Title: General Help with Crystal   
Name: Elizabeth
Date: 2010-04-27 3:18:06 PM
Comment:
Very helpful. A get started article allowing me to use Crystal without a lot of time spent learning.
Title: Article   
Name: Junaid
Date: 2010-03-22 9:42:00 AM
Comment:
It is such a useful to us. as i am a beginner so i got a very clear idea about Crystal Report.
Title: article   
Name: dave himanshu
Date: 2010-03-22 6:55:26 AM
Comment:
such a good job!!!
Title: deploy crystal report   
Name: john
Date: 2010-03-16 8:06:24 PM
Comment:
Great article. Thanks.

Once I have created a crystal report using visual studio 2008, what do I have to deploy to my server for the report to work on a shared hosting server?

Product Spotlight
Product Spotlight 



Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-05-26 12:05:39 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search