Setting the Connection String Programmatically on a Crystal Reports ReportDocument

Programmatically setting the connection string for a Crystal Reports ReportDocument will allow you to have the report automatically use the active connection string for the rest of the application (as in previous posts). In this case, the report is created using a method that is triggered by clicking a button on a form. The log on information must be applied to each table in the ReportDocument.

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim crReportDocument As ReportDocument
            crReportDocument = New ReportDocument
            crReportDocument.Load(<>)

            Dim sConn As SqlConnectionStringBuilder = New SqlConnectionStringBuilder(<>)

            Dim tables As CrystalDecisions.CrystalReports.Engine.Tables = crReportDocument.Database.Tables

            For Each table As CrystalDecisions.CrystalReports.Engine.Table In tables
                Dim tableLogOnInfo As CrystalDecisions.Shared.TableLogOnInfo = table.LogOnInfo
                tableLogOnInfo.ConnectionInfo.ServerName = sConn.DataSource
                tableLogOnInfo.ConnectionInfo.DatabaseName = sConn.InitialCatalog
                tableLogOnInfo.ConnectionInfo.IntegratedSecurity = True
                table.ApplyLogOnInfo(tableLogOnInfo)
            Next

            ' ...

       End Sub

Classics of Software Engineering

Even though I have been writing programs for most of my life, that does not mean that my programs have always been written well. Only following the standard prohibitions on spaghetti code and documenting well does not a good program make.

The best advice I ever got about writing programs was to read two books:

1. The Pragmatic Programmer, by Andy Hunt and Dave Thomas
2. Code Complete, 2nd Edition, by Steve McConnell

After applying the techniques from these books, your programs will be much easier to maintain, and much more efficient.

A third book that is also quite helpful is Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides (aka the Gang of Four).

These books are all available at Amazon.com in paper or Kindle format.

%d bloggers like this: