Crystal Reports users have the ability to save reports they
created as *.rpt files, just as we do when we build them inside of Visual Studio.
The Crystal Reports Developer API allows you to instantiate a ReportDocument
and then call its Load method to pull in a saved rpt file. Therefore, it is
possible to load a report created with the end-user product into a custom .NET
application with the following code.
Dim rptDoc As New CrystalDecisions.CrystalReports.Engine.ReportDocument
rptDoc.Load(“C:\Reports\Report1.rpt”)
The CrystalReportViewer, the control which is embedded into
a Windows Form has a ReportSource property which is used at design time to view
instantiated reports. By setting the ReportSource property to the newly created
ReportDocument, it is then possible to display the user-built report in your
custom application.
CrystalReportViewer1.ReportSource = rptDoc
When the report is created and saved, by default, the data
is saved along with the report. This may be useful for preserving the state of
your data; however, it is more likely that later viewers of the report will
want to see current data.
Therefore, the last key part of building this solution is
allowing the report to display live data whenever it is viewed. This is done by
re-establishing the report’s connection to the database and then refreshing the
report. Rather than using a standard connection string, you will need to pass
the key elements of a connection string (server name or IP, database name,
integrated security setting) to a SetConnection method within the report’s
object model. While you will need to supply the server name (or IP address),
the database name and Integrated Security option are stored as metadata in the
saved report. The following code shows how to extract that information from the
above report and use it to re-connect to the database. Once the connection has
been made, call the ReportDocument’s Refresh method to populate the report with
the current data.
With rptDoc.DataSourceConnections(0)
Dim dbname As String = .DatabaseName
Dim integrated As Boolean = .IntegratedSecurity
.SetConnection(“MyServer”, dbname, integrated)
End With
rptDoc.Refresh()