Crystal Reports Online Training

Learn Online, Anytime, Anywhere

Step-by-step online tutorials.

17.02 Logging on to Databases

Logging On To Databases Simplified

Crystal Reports is designed so that the user ID you entered at design time is saved with the report file, but not the password. If you are printing from a non-secure data source, this doesn’t affect you. If the data source is secure, you are prompted with a dialog box to enter the login credentials. This is done so that the security of your database isn’t compromised. You can prevent this dialog box from appearing by setting the user credentials during runtime. This lets you manage security in a way that conforms to your corporation’s policies.

Crystal Reports makes it very easy to connect to a secure data source. Use theSetDatabaseLogon() method of the ReportDocument class to pass a User ID and Password to the database. Listing 17-1 shows a simple example that passes a User ID of “sa” and a Password of “1234” to the report.

Listing 17-1. Using the SetDatabaseLogon() method to login to a database.
[VB.NET]
Dim myReport As New CrystalDecisions.CrystalReports.Engine.ReportDocument
myReport.Load("report.rpt")
myReport.SetDatabaseLogon("sa", "1234")
CrystalReportViewer1.ReportSource = myReport
[C#]
CrystalDecisions.CrystalReports.Engine.ReportDocument myReport = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
myReport.Load("report.rpt");
myReport.SetDatabaseLogon("sa", "1234");
CrystalReportViewer1.ReportSource = myReport;

The SetDatabaseLogon() method also passes the security credentials to all subreports that are associated with the main report. Thus, you only have to call it once.

If logging into a secure MS Access database, the SetDatabaseLogon() method only needs the password to log in. You can pass an empty string as the User ID.

Unfortunately, there are situations where the SetDatabaseLogon() method can’t be used. They are as follows:

  • Each table connects to a different database.
  • Subreports use different security credentials.
  • Changing the server name or database name during runtime.
  • Using the CrystalReportsViewer class to pass security credentials.

In these circumstances, you need to work directly with the classes within database object model. By accessing the methods and properties of the individual classes, you get a control over which data sources the report connects to and the security credentials it uses to access the data.