Click here to Skip to main content
15,868,016 members
Articles / Desktop Programming / Windows Forms

Reporting XML data using Crystal Reports

Rate me:
Please Sign up or sign in to vote.
4.04/5 (14 votes)
22 Oct 2007CPOL9 min read 136.8K   49   13
This article will show you how to report XML data with Crystal Reports and a Windows Forms client.

Overview

This article will show you how to report XML data with Crystal Reports and a Windows Forms client.

Image 1

Figure: 1 – Example in run-time mode

Introduction

Reporting on data sources such as MS Access, SQL Server, and Oracle is common with Crystal Reports (CR). How about XML as a data source? Well, sure, you might be wondering how to do that. Is it even possible? Well, with the help of this article, I'll show you how to use an XML data source and report on it using Crystal Reports.

I assume the reader has a basic understanding of the Visual Studio (VS) 2005 IDE and Crystal Reports. You should also be comfortable writing code in C#. A basic understanding of XML schema and ADO.NET is desirable.

What is XML Data?

Before we see the demo, let's get to know what XML data is! If I can put it in simple words, XML stands for Extensible Markup Language. It is an initiative by W3C to allow the exchange of information which is easy to understand by both humans and computers. Information stored in XML format can work on cross platform scenarios. For example, if you have information in XML format, it is easy to share between the UNIX and the Windows platforms. The data inside an XML file is presented with user defined tags. Following is a partial listing from the sample XML file which I am using with this demo:

XML
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>

As you can see, each <CD> tag is equivalent to a row with information related to CD. Further, each column is uniquely identified as a tag. You can learn more on XML from here: http://www.w3schools.com/xml/xml_whatis.asp. All right, let's start with our demo and see how easy it is to report on XML data with Crystal Reports and Windows Forms.

Step 1: Let's Create a Windows Application Project

If VS 2005 IDE is not already started, then you can launch the IDE by clicking on the Windows Start button -> All Programs -> Microsoft Visual Studio 2005, click on the icon Microsoft Visual Studio 2005. You may have other ways to lunch the IDE, such as clicking a desktop shortcut, and so on.

Please do the following steps to create a Windows Application Project:

  1. Click on menu File -> New -> Project…, or you can press the hot key Ctrl + Shift + N (please see Figure 2).
  2. From the New Project dialog box, select Visual C# -> Windows.
  3. From Templates, select Windows Application.
  4. Please give a name to the application; I've called the project "XMLCRReport". You may choose a different location for storing the application files as per your preference. Please see Figure 2 for an illustration of the naming process.
  5. Click on the OK button to finish the process. VS 2005 will create a new project and add Form1 to it by default.

Image 2

Figure: 2 – Process to create a new Windows Application Project

Let's set the properties of Form1 according to Table 1. In case the property toolbox is not visible in the IDE, you may hit the F4 key to make it visible. Please make sure to select Form1 before applying changes to the properties using the property toolbox.

Table 1. Properties of Form1
PropertyValue
TextReporting XML data using Crystal Reports
Size700,300

Step 2: Let's Add CrystalReportViewer to Form1

The Crystal Report Viewer (CRV) control is needed for us to show the report to the user. Report Viewer gives life to your reports. It not only previews the output, it also allows you to generate information in the various popular formats (PDF, Excel, etc.). You can also take a hard copy print of the report while you are viewing the output.

You can add a CrystalReportViewer to Form1 as follows:

  1. Make sure Form1 is currently open in designer.
  2. Drag ToolBox -> CrystalReports -> CrystalReportViewer and drop it on Form1. This step will create a new instance of CrystalReportViewer with the name crystalReportViewer1. You can name it anything; I'll stick with the default.

After step 1 and step 2, your project should look similar to Figure 3.

Image 3

Figure: 3 – Form1 designer surface after adding CRV

Step 3: Add a DataSet to the Project

Although there are different ways you can get data to a CrystalReportViewer, I'll show you here the DataSet technique. Let's go ahead and add a DataSet to the project. The following step is needed to have a DataSet added to the project:

Select Add -> New Item -> DataSet from Solution Explorer. Change the name from DataSet1 to dsCDCatalog and click the Add button. Please cancel the TableAdapter Configuration wizard; we'll add a DataTable using the DataSet Designer.

Let's add the DataTable to our newly created DataSet. The DataTable is essential to load the reporting data; we'll use information from the DataSet/DataTable while designing the report. The following step is required to have a DataTable added to the DataSet (dsCDCatalog):

Double-click on dsCDCatalog from Solution Explorer; it'll open the designer view. Right-click the designer surface and select Add -> DataTable. Click the header and change the name to dtCDCatalog (see Figure 4).

Image 4

Figure: 4 – Add DataTable to DataSet

Let's start adding columns to the DataTable (dtCDCatalog). Your designer screen should look like Figure 5. Right-click on dtEmployee and select Add -> Column to start adding columns to the DataTable.

Image 5

Figure: 5 – Add columns to DataTable

Repeat the action for the following columns:

  • Title (String)
  • Artist (String)
  • Country (String)
  • Company (String)
  • Price (Double)
  • Year (String)

As you are adding columns, by default they will be the String data type. Go to the Properties window after selecting a column to change it from String to Int32. After you are done with adding columns, it should look similar to Figure 6.

Image 6

Figure: 6 – DataTable after adding needed columns

Step 4: Add a report to the project

So far we've created the project, and added a CrystalReportViewer and a DataSet. It's time to work on the report. Following are the steps required to add a report (rptXMLData.rpt):

Select Add -> New Item -> Crystal Report from Solution Explorer. Change the name from CrystalReport1.rpt to rptXMLData.rpt and click the Add button to complete the action. A dialog box of Crystal Reports Gallery will appear, select the "As a Blank Report" option, and click the OK button to complete the process to add a report.

By default, you will see the rptXMLData.rpt is open for you in designer mode and its default setting. For this example, I'll make use of only the page header and footer. I'll reduce the height of the report header and footer. Typically, after all this, your report designer should look similar to Figure 7.

Image 7

Figure: 7 – Newly added report in design mode

To add a report to a project is easy, the challenge is to fill in the empty report layout. Whether this is your first report or you are a reporting junkie like me, we must deal with the most basic building blocks of report writing; that is, the header, the detail, and the footer.

Typically, reports are designed with a specific page size and layout in mind. Our report is Letter size and Portrait layout. You can explore the various properties attached to the report layout by right-clicking anywhere on the open designer surface (gray area) and selecting Report and Design Properties.

It is always advisable to draw a prototype of your report on a paper before you start the design process. As you can see in Figure 1, we have the report name and report date in the header section. The body section has the employee list information; the footer carries the page numbers.

Header section

Our header section consists of five Text Objects, two Line Objects, and a Special Field. Please drag and drop a Text Object and Line Object from Toolbox -> Crystal Reports. You can drag and drop "Print Date", a special field, from Field Explorer -> Special Fields -> Print Date. You'll also notice that I've changed the color and font after placing the report object on the designer surface. Please make sure your header looks similar to Figure 8.

Image 8

Figure: 8 – Report header and footer

Footer section

The footer section is simple, just one special field and one Line Object. As you've done with the header section, you can add a Line Object from Toolbox -> Crystal Reports. Similarly, you can drag and drop "Page N of M", a special field, from Field Explorer -> Special Fields -> Page N of M. Please see Figure 8 and make sure the footer looks similar.

Detail section

The details section of the report will have the CD catalog list details. Now the question is, from where will we get the data for it? Well, as you know, in the beginning, we added a DataSet to this project, we will use this DataSet as the source of data to our report.

Adding a DataSet as the source of data to a report is easy. You'll start with right-clicking on any open area on Report Designer -> Database -> Database Expert… As a result of this action, a Database Expert dialog box will appear. You can click on Project Data and expand the node ADO.NET DataSet. Please select the dtCDCatalog DataTable from our DataSet and click on the ">" button to move it to the Selected Tables section on the right-hand side (please see Figure 9).

Image 9

Figure: 9 – Adding a DataSet as a report data source

Once a report source is specified, all we have to do is drag and drop the fields from the DataTable inside the Detail section on the report designer surface. You can drag and drop the Title from Field Explorer inside the Detail section.

As you drag and drop the fields inside the Detail section, you'll notice that the title of the filed is also added to the report designer. As we've already taken care of the field header, just delete the default added field header. Please make sure the final report designer layout looks similar to Figure 10.

Image 10

Figure: 10 – Final repot design layout

Although the report design looks complete, we have not yet worked on the hierarchical functionality of this report. As you can see in Figure 1, all the employee names should form a hierarchy based on the ManagerID association.

Step 5: C# interface code

All right, we have got all we needed as a report design. Please make sure to have the following C# code behind Form1.cs:

C#
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
namespace XMLCRReport 
{ 
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
        InitializeComponent(); 
    } 
    private void Form1_Load(object sender, EventArgs e) 
    { 
        DataSet dsReport = new dsCDCatalog(); 
        // create temp dataset to read xml information 
        DataSet dsTempReport = new DataSet(); 
        try 
        { 
            // using ReadXml method of DataSet read XML data from books.xml file 
            dsTempReport.ReadXml(@"C:\articles\XmlCrystalReport\cd_catalog.xml"); 
            // copy XML data from temp dataset to our typed data set 
            dsReport.Tables[0].Merge(dsTempReport.Tables[0]); 
            //prepare report for preview 
            rptXMLData rptXMLReport = new rptXMLData(); 
            rptXMLReport.SetDataSource(dsReport.Tables[0]); 
            crystalReportViewer1.DisplayGroupTree = false; 
            crystalReportViewer1.ReportSource = rptXMLReport; 
        } 
        catch (Exception ex) 
        { 
            MessageBox.Show(ex.Message); 
        } 
    } 
} 
}

Let's build and run the example

Let's build the project. You can build a project in several different ways if you just have one project in a solution; building the solution and project are the same. You can click on the small green Play button on the main toolbox or hit F5 on the keyboard to start the application in run time. If all goes well, then your report output should look something similar to Figure 1. If you face any issues, then I'd advice you to validate all the steps and try again.

Conclusion

You can see how simple it is to present XML data using Crystal Reports. Thank you for reading; as always, I'm looking for comments and suggestions. Feel free to drop them at asif.blog@gmail.com.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect FeatherSoft Inc.
Canada Canada
Asif Sayed has over twenty + years experience in software development and business process architecture. He has a consulting firm in Toronto, Canada. His firm provides IT solutions to all sizes of industries. He also teaches .NET technologies at Centennial College in Scarborough, Ontario. Recently he has become member of team as a subject matter experts with Microsoft's Learning Division. He has a book published by Apress with the Title "Client-Side Reporting with Visual Studio in C#".

My blog: http://www.dotnetsme.com
My Website: http://www.feathersoft.ca

Comments and Discussions

 
GeneralRe: Reporting XML data using Crystal Reports Pin
Ankitaaguggi15-Sep-11 2:39
Ankitaaguggi15-Sep-11 2:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.