Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change the connection of a Crystal Report

I am using CrystalReportViewer and CrystalReportSource to load and display an .rpt file in my application.

The situation I have is this:

Say a person created a crystal report outside of my application and set its datasource to database A. I then use that .rpt file in my application but I need to bind it to a different database (identical to the original one in terms of table structure and column names but with a different connection string using a different user name and password). How do I do that in C#?

Currently I load the report using:

this.CrystalReportSource1.ReportDocument.Load(reportsSubfolder + report.ReportFileName);
//it is here that I need to change the connection data of the report.
like image 777
suzi167 Avatar asked Sep 11 '09 15:09

suzi167


1 Answers

I use a function like the following to assign the connection information at runtime.

private void SetDBLogonForReport(CrystalDecisions.Shared.ConnectionInfo connectionInfo, CrystalDecisions.CrystalReports.Engine.ReportDocument reportDocument)
{
    CrystalDecisions.CrystalReports.Engine.Tables tables = reportDocument.Database.Tables;

    foreach (CrystalDecisions.CrystalReports.Engine.Table table in tables)
    {
        CrystalDecisions.Shared.TableLogOnInfo tableLogonInfo = table.LogOnInfo;

        tableLogonInfo.ConnectionInfo = connectionInfo;
        table.ApplyLogOnInfo(tableLogonInfo);
    }
}

You should be able to simply create a new ConnectionInfo object with the necessary info and pass it into the function along with the report document. Hope this helps.

like image 95
Dusty Avatar answered Oct 25 '22 13:10

Dusty