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.