Bean Software Logo
ASP.NET Database Search Control
 Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

Crystal Reports in ASP.NET

Crystal Reports is the standard reporting tool for Visual Studio .NET used to display data of presentation quality. You can display multiple-level totals, charts to analyze data, and much more in Crystal Reports. Creating a Crystal Report requires minimal coding since it is created in Designer interface. It is available as an integrated feature of Microsoft Visual Studio .NET, Borland Delphi, and C#Builder.

 

Advantages of Crystal Reports

Some of the major advantages of using Crystal Reports are:

1. Rapid report development since the designer interface would ease the coding work for the programmer.

2. Can extend it to complicated reports with interactive charts and enhance the understanding of the business model

3. Exposes a report object model, can interact with other controls on the ASP.NET Web form

4. Can programmatically export the reports into widely used formats like .pdf, .doc, .xls, .html and .rtf

Implementation Models

Crystal Reports need database drivers to connect to the data source for accessing data. Crystal Reports in .net support two methods to access data from a data source:

The Pull Method

When this model is used to access data from the data source, the database driver directly retrieves the data from the data source. This model does not require the developer to write code for creating a connection and retrieving data from the data source. It is the Crystal report that manages the SQL commands for connecting by using the specified driver.

The Push Method

When this model is used to access data from data source, the developer writes the code to connect to the data source and retrieve data. The data from the data source is cached in dataset and multiple crystal reports accesses data from the dataset. The performance can be optimized in this manner by using connection sharing and manually limiting the number of records that are passed on to the report.

Crystal Reports Types

Crystal Report Designer can load reports that are included into the project as well as those that are independent of the project.

Strongly-typed Report

When you add a report file into the project, it becomes a "strongly-typed" report. In this case, you will have the advantage of directly creating an instance of the report object, which could reduce a few lines of code, and cache it to improve performance. The related .vb file, which is hidden, can be viewed using the editor's "show all files" icon in the Solution Explorer.

Un-Typed Report

Those reports that are not included into the project are "un-typed" reports. In this case, you will have to create an instance of the Crystal Report Engine's "ReportDocument" object and manually load the report into it.

Creating Crystal Reports

You can create a Crystal Report by using three methods:

1. Manually i.e. from a blank document
2. Using Standard Report Expert
3. From an existing report

Using Pull Method

Creating Crystal Reports Manually.

We would use the following steps to implement Crystal Reports using the Pull Model:

1. Create the .rpt file (from scratch) and set the necessary database connections using the Crystal Report Designer interface.

2. Place a CrystalReportViewer control from the toolbox on the .aspx page and set its properties to point to the .rpt file that we created in the previous step.

3. Call the databind method from your code behind page.

I. Steps to create the report i.e. the .rpt file

1) Add a new Crystal Report to the web form by right clicking on the "Solution Explorer", selecting "Add" --> "Add New Item" --> "Crystal Report".

2) On the "Crystal Report Gallery" pop up, select the "As a Blank Report" radio button and click "ok".

3) This should open up the Report File in the Crystal Report Designer.

4) Right click on the "Details Section" of the report, and select "Database" -> "Add/Remove Database".

5) In the "Database Expert" pop up window, expand the "OLE DB (ADO)" option by clicking the "+" sign, which should bring up another "OLE DB (ADO)" pop up.

6) In the "OLE DB (ADO)" pop up, Select "Microsoft OLE DB Provider for SQL Server" and click Next.

7) Specify the connection information.

8) Click "Next" and then click "Finish"

9) Now you should be able to see the Database Expert showing the table that have been selected

10) Expand the "Pubs" database, expand the "Tables", select the "Stores" table and click on ">" to include it into the "Selected Tables" section.

Note: If you add more than one table in the database Expert and the added tables have matching fields, when you click the OK button after adding the tables, the links between the added tables is displayed under the Links tab. You can remove the link by clicking the Clear Links button.

11) Now the Field Explorer should show you the selected table and its fields under the "Database Fields" section, in the left window.

12) Drag and drop the required fields into the "Details" section of the report. The field names would automatically appear in the "Page Header" section of the report. If you want to modify the header text then right click on the text of the "Page Header" section, select "Edit Text Object" option and edit it.

13) Save it and we are through.

II. Creating a Crystal Report Viewer Control

1) Drag and drop the "Crystal Report Viewer>" from the web forms tool box on to the .aspx page

2) Open the properties window for the Crystal Report Viewer control.

3) Click on the [...] next to the "Data Binding" Property and bring up the data binding pop-up window

4) Select "Report Source".

5) Select the "Custom Binding Expression" radio button, on the right side bottom of the window and specify the sample .rpt filename and path as shown in the fig.

6) You should be able to see the Crystal Report Viewer showing you a preview of actual report file using some dummy data and this completes the inserting of the Crystal Report Viewer controls and setting its properties.

Note: In the previous example, the CrystalReportViewer control was able to directly load the actual data during design time itself as the report was saved with the data. In this case, it will not display the data during design time as it not saved with the data - instead it will show up with dummy data during design time and will fetch the proper data only at run time.

7) Call the Databind method on the Page Load Event of the Code Behind file (.aspx.vb). Build and run your .aspx page. The output would look like this.

Using a PUSH model

1. Create a Dataset during design time.

2. Create the .rpt file (from scratch) and make it point to the Dataset that we created in the previous step.

3. Place a CrystalReportViewer control on the .aspx page and set its properties to point to the .rpt file that we created in the previous step.

4. In your code behind page, write the subroutine to make the connections to the database and populate the dataset that we created previously in step one.

5. Call the Databind method from your code behind page.

I. Creating a Dataset during Design Time to Define the Fields of the Reports

1) Right click on "Solution Explorer", select "Add" --> select "Add New Item" --> Select "DataSet"

2) Drag and drop the "Stores" table (within the PUBS database) from the "SQL Server" Item under "Server Explorer".

3) This should create a definition of the "Stores" table within the Dataset

The .xsd file created this way contains only the field definitions without any data in it. It is up to the developer to create the connection to the database, populate the dataset and feed it to the Crystal Report.

II. Creating the .rpt File

4) Create the report file using the steps mentioned previously. The only difference here is that instead of connecting to the Database thru Crystal Report to get to the Table, we would be using our DataSet that we just created.

5) After creating the .rpt file, right click on the "Details" section of the Report file, select "Add/Remove Database"

6) In the "Database Expert" window, expand "Project Data" (instead of "OLE DB" that was selected in the case of the PULL Model), expand "ADO.NET DataSet", "DataSet1", and select the "Stores"table.

7) Include the "Stores" table into the "Selected Tables" section by clicking on ">" and then Click "ok"

8) Follow the remaining steps to create the report layout as mentioned previously in the PULL Model to complete the .rpt Report file creation

III. Creating a CrystalReportViewer Control

9) Follow the steps mentioned previously in the PULL Model to create a Crystal Report Viewer control and set its properties.

Code Behind Page Modifications: 10) Call this subroutine in your page load event:

    Sub BindReport()
        Dim myConnection As New SqlClient.SqlConnection()
        myConnection.ConnectionString = "server= (local)\NetSDK;database=pubs;Trusted_Connection=yes"
        Dim MyCommand As New SqlClient.SqlCommand()
        MyCommand.Connection = myConnection
        MyCommand.CommandText = "Select * from Stores"
        MyCommand.CommandType = CommandType.Text
        Dim MyDA As New SqlClient.SqlDataAdapter()
        MyDA.SelectCommand = MyCommand
        Dim myDS As New Dataset1()
        'This is our DataSet created at Design Time     
        MyDA.Fill(myDS, "Stores")
        'You have to use the same name as that of your Dataset that you created during design time
        Dim oRpt As New CrystalReport1()
        ' This is the Crystal Report file created at Design Time
        oRpt.SetDataSource(myDS)
        ' Set the SetDataSource property of the Report to the Dataset
        CrystalReportViewer1.ReportSource = oRpt
        ' Set the Crystal Report Viewer's property to the oRpt Report object that we created
    End Sub

Note: In the above code, you would notice that the object oRpt is an instance of the "Strongly Typed" Report file. If we were to use an "UnTyped" Report then we would have to use a ReportDocument object and manually load the report file into it.

Enhancing Crystal Reports

Accessing filtered data through Crystal reports

Perform the following steps for the same.

1. Generate a dataset that contains data according to your selection criteria, say "where (cost>1000)".

2. Create the Crystal Report manually. It would look like this.

3. Right Click Group Name fields in the field Explorer window and select insert Group from the shortcut menu. Select the relevant field name from the first list box as shown.

The group name field is created, since the data needs to be grouped on the basis of the cat id say.

4. A plus sign is added in front of Group Name Filed in the field explorer window. The Group Name Field needs to be added to the Group Header section of the Crystal Report. Notice this is done automatically.

5. Right Click the running total field and select new. Fill the required values through > and the drop down list.

6. Since the count of number of categories is to be displayed for the total categories, drag RTotal0 to the footer of the report.

Create a formula

Suppose if the report required some Calculations too. Perform the following steps:

1. Right Click the formula Fields in the field explorer window and select new. Enter any relevant name, say percentage.

2. A formula can be created by using the three panes in the dialog box. The first pane contains all the crystal report fields, the second contains all the functions, such as Avg, Sin, Sum etc and the third contains operators such as arithmetic, conversion and comparison operators.

3. Double click any relevant field name from the forst pane, say there's some field like advance from some CustOrder table. Then expand Arithmetic from the third pane and double click Divide operator.

4. Double click another field name from the first which you want to use as divisor of the first field name already selected say it is CustOrder.Cost.

5. Double Click the Multiply from third pane and the type 100.

6. The formula would appear as {CustOrder.Advance}/{ CustOrder.Cost} * 100.

7. Save the formula and close Formula Editor:@Percentage dialog box.

8. Insert the percentage formula field in the details pane.

9. Host the Crystal report.

Exporting Crystal reports

When using Crystal Reports in a Web Form, the CrystalReportViewer control does not have the export or the print buttons unlike the one in Windows Form. Although, we can achieve export and print functionality through coding. If we export to PDF format, Acrobat can handle the printing for us, as well as saving a copy of the report.

You can opt to export your report file into one of the following formats:

  • PDF (Portable Document Format)

  • DOC (MS Word Document)

  • XLS (MS Excel Spreadsheet)

  • HTML (Hyper Text Markup Language - 3.2 or 4.0 compliant)

  • RTF (Rich Text Format)

To accomplish this you could place a button on your page to trigger the export functionality.

When using Crystal Reports in ASP.NET in a Web Form, the CrystalReportViewer control does not have the export or the print buttons like the one in Windows Form. We can still achieve some degree of export and print functionality by writing our own code to handle exporting. If we export to PDF format, Acrobat can be used to handle the printing for us and saving a copy of the report.

Exporting a Report File Created using the PULL Model

Here the Crystal Report takes care of connecting to the database and fetching the required records, so you would only have to use the below given code in the Event of the button.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim myReport As CrystalReport1 = New CrystalReport1()
        'Note : we are creating an instance of the strongly-typed Crystal Report file here.
 
        Dim DiskOpts As CrystalDecisions.Shared.DiskFileDestinationOptions = New CrystalDecisions.Shared.DiskFileDestinationOptions
        myReport.ExportOptions.ExportDestinationType = CrystalDecisions.[Shared].ExportDestinationType.DiskFile
        ' You also have the option to export the report to other sources
        ' like Microsoft Exchange, MAPI, etc.       
 
        myReport.ExportOptions.ExportFormatType = CrystalDecisions.[Shared].ExportFormatType.PortableDocFormat
        'Here we are exporting the report to a .pdf format.  You can
        ' also choose any of the other formats specified above.
 
        DiskOpts.DiskFileName = "c:\Output.pdf"
        'If you do not specify the exact path here (i.e. including
        ' the drive and Directory),
        'then you would find your output file landing up in the
        'c:\WinNT\System32 directory - atleast in case of a
        ' Windows 2000 System
        myReport.ExportOptions.DestinationOptions = DiskOpts
        'The Reports Export Options does not have a filename property
        'that can be directly set. Instead, you will have to use
        'the DiskFileDestinationOptions object and set its DiskFileName
        'property to the file name (including the path) of your  choice.
        'Then you would set the Report Export Options
        'DestinationOptions property to point to the
        'DiskFileDestinationOption object.
 
        myReport.Export()
        'This statement exports the report based on the previously set properties.
 
    End Sub

Exporting a Report File Created Using the PUSH Model

Using Push Model, the first step would be to manually create connections and populate the Dataset, and set the Report's "SetDataSource" property to the required Dataset (in the same manner as shown in the Push Model example before). The next step would be to call the above given Export.

Crystal Reports alternatives

Many people found Crystal Reports hard to learn and use and they are seeking for simpler alternatives. Very popular Crystal Reports competitor is SQL Server Reporting Services (SSRS). Also, you can try some of many commercial alternatives.


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   


comments powered by Disqus

Related articles:

1. Implementing Web Service Clients
2. Encrypting Connection Strings in web.config file
3. How To Use AdRotator Control
4. Introducing to Help System in .NET