Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Change the Data Source of a Crystal Reports Report at Run-time using C#

5.00/5 (2 votes)
19 Oct 2011CPOL 41.3K  
This is a common issue that development teams face when reports are being deployed to the production environment.

It’s a known fact that in Crystal Reports, if you try to display details, using data in a SQL Server database other than the one that you’ve used to design the report, either you have to set the database location or refresh the report. This is a common issue that development teams face when reports are being deployed to the production environment.

But this can be prevented using the following method.

The following namespaces are required:

C#
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

And we have to assign the required SQL Server information to each table/view of the report, sub reports, and the report viewer.

Use the following code:

C#
SQLReport report = new SQLReport();
 
//Get SQL Server Details
string zServer = @"SERVER_NAME";
string zDatabase = @"DATABASE";
string zUsername = @"USER";
string zPassword = @"PASSWORD";

ConnectionInfo ciReportConnection = new ConnectionInfo();

ciReportConnection.ServerName = zServer;
ciReportConnection.DatabaseName = zDatabase;
ciReportConnection.UserID = zUsername;
ciReportConnection.Password = zPassword;

//Assign data source details to tables

foreach (Table table in report.Database.Tables) {
     table.LogOnInfo.ConnectionInfo = ciReportConnection;
     table.ApplyLogOnInfo(table.LogOnInfo);
}

foreach (ReportDocument subrep in report.Subreports) {
     foreach (Table table in subrep.Database.Tables) {
         table.LogOnInfo.ConnectionInfo = ciReportConnection;
         table.ApplyLogOnInfo(table.LogOnInfo);
     }
}

//Assign data source details to the report viewer
if (this.crystalReportViewer1.LogOnInfo != null) {
     TableLogOnInfos tlInfo = this.crystalReportViewer1.LogOnInfo;
     foreach (TableLogOnInfo tbloginfo in tlInfo) {
         tbloginfo.ConnectionInfo = ciReportConnection;
     }
}
 
crystalReportViewer1.ReportSource = report;
crystalReportViewer1.Refresh();

License

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