Search code examples
c#winformscrystal-reports

How to set database name dynamically for a crystal report using C#?


I have a C# windows application in which there are many crystal reports.I call and show them using the following piece of code :

rptDDCollection rpt = new rptDDCollection();
            rpt.SetDatabaseLogon(Connect.sDatabaseUserName, DLL.Connect.sDatabasePassword, "", Connect.sCurrentDatabase);
            rpt.RecordSelectionFormula = "";
            frmReports frm = new frmReports();
            frm.crViewer1.DisplayGroupTree = false;
            frm.crViewer1.ReportSource = rpt;
            frm.crViewer1.SelectionFormula = rpt.RecordSelectionFormula;                
            frm.crViewer1.Show();
            frm.Show();

Now, the issue is that I have 2 databases to work on.Things work fine with one database.I have to use the same report but very often I need to view data from the other database.The database engine is SQL server.While searching on the net and on stack overflow, I found suggestions to set the database name dynamically through code.What should be done to achieve what I want in this case?


Solution

  • I worked this around by setting database name for the tables in the report.I made one change in the actual code above.I created a method called ApplyLogonInfo and passed the report object to it.Inside the method I wrote the code for setting database name for the report tables dynamically.This is the modified code:

    rptDDCollection rpt = new rptDDCollection();
            rpt.SetDatabaseLogon(Connect.sDatabaseUserName, DLL.Connect.sDatabasePassword, "", Connect.sCurrentDatabase);
            ApplyLogOnInfo(rpt);     
            rpt.RecordSelectionFormula = "";  
            frmReports frm = new frmReports();
            frm.crViewer1.DisplayGroupTree = false;
            frm.crViewer1.ReportSource = rpt;
            frm.crViewer1.SelectionFormula = rpt.RecordSelectionFormula;                
            frm.crViewer1.Show();
            frm.Show();
    

    Below is the newly created method:

    public static void ApplyLogOnInfo(ReportClass rpt)
        {
            TableLogOnInfo info = new TableLogOnInfo();
            info.ConnectionInfo.DatabaseName = Connect.sCurrentDatabase;
            for (int i = 0; i < rpt.Database.Tables.Count; i++)
            {
                rpt.Database.Tables[i].ApplyLogOnInfo(info);
            }
        }
    

    sCurrentDatabase is the name of the database that has been currently selected for viewing.

    This enabled me to set the database name dynamically, and now I can work with 2 (or in general multiple) databases and view the data from whichever database I wish to see.