Crystal Reports Online Training

Learn Online, Anytime, Anywhere

Step-by-step online tutorials.

14.04 ASP.NET Template

ASP.NET Template

Printing reports within an ASP.NET application requires a slightly different template than the Windows template shown in Listing 14-1. Reports shown on an ASP.NET page are unique in that each time the user moves to a new report page, the web page gets reloaded. If a report is resource intensive, then this can slow performance or tie up resources. For example, a report that connects to SQL Server will open a new connection each time the page is loaded. Fixing this problem requires saving the report to the Session collection and using the IsPostBack function. When doing ASP.NET development, use the template in Listing 14-2 for optimizing reports.

Listing 14-2. Template for ASP.NET pages.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim MyReport As CrystalDecisions.CrystalReports.Engine.ReportDocument
If Not IsPostBack Then
MyReport = New CrystalReport1
‘Call all report modification code here.
‘For illustration purposes, I'm calling a generic method that changes
‘the report title. The code for ModifyTitle() isn't shown here.
ModifyTitle(MyReport, "Runtime Demo")
Session("MyReport") = MyReport
Else
‘Get the report object from the Session collection
MyReport = CType(Session("MyReport"), CrystalDecisions.CrystalReports.Engine.ReportDocument)
End If
CrystalReportViewer1.ReportSource = MyReport
End Sub

If a report connects to an MS Access database, you might notice that the record lock file (.MDL) isn’t released when the page unloads. If the report connects to SQL Server, then it leaves the connection open. This is because the connection is closed when the report is disposed of during .NET’s garbage collection process. To dispose of an object when the page unloads, you have to force garbage collection during the Unload() event. Listing 14-3 shows how this is done.

Listing 14-3. Forcing garbage collection in an ASP.NET page.
Private Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Unload
MyReport.Close()
MyReport.Dispose()
GC.Collect()
End Sub

There are a couple points of interest here. The first assumes that the MyReport object variable has been declared at the class level. The template shown in Listing 14-2 declares the MyReport object variable at the procedure level. This declaration will have to be moved to the class level. The second point is that if you are connecting to SQL Server and using VB.NET, this code doesn’t work. Disposing the report object closes the connection to the database and you have to login again (thus defeating the purpose of Listing 14-2). You have to clean up resources on another web page. If you are using the C# listings shown at the end of this chapter, this code will work for SQL Server.