I'd like to share how to make a report using Crystal Report, and connect it from VB here, since there has been several friends asking about this.
There are actually several ways to connect VB and Crystal Report, ones of which that I've ever used are using TTX and ODBC.
I'd like to share the usage of TTX here. I use Crystal Report 8.5, but it's more or less the same as the other versions.
Like it's data source type - Field Definition Only - implies, it makes a .ttx file to define the fields used in the report. Thus, when creating a report, we have to make a .ttx file that contains all the fields and type of the fields used in the report.
The advantages of this method are:
1. Flexible, we don't have to change the report if there is any changes on the logic while retrieving the data.
2. We only have to define the data type, that's all, and do the code in the application.
These are the steps need to be done for the report:
1. Run Crystal Report, choose Create a New Crystal Report Document [As a Blank Report].
2. Choose the type of the data source: Field Definition Only.
3. It will ask to browse for a text file or make a new file, I'll make a new one.
Just insert the Field Name and the Field Type to be used in the report. Make sure the field name and the field type is correct. Add all fields used. When finished, click the close icon of the form. It will ask to save the file, then click OK.
4. Click Add to add the .ttx file to the report, then click Close.
5. Start designing the report by inserting the fields used in the report then save it.
I use the table [Customers] from the Northwind database.
I'll try to print Customers data by Country.
PS: I use ADODB for the database connection.
These are the steps in the VB:
1. Add Crystal Report component to the application by pressing ctrl+T or go to menu Projects -> Components. On the Controls tab, check [Crystal Report Control], then press ok. A crystal report component will be added to the toolbox window.
2. Drag the component to the form.
3. The small programs will look like this.
4. Here's the code on the print button event:
The name of the Controls:
combo : cmbCountry
command button : cmdPrint
Private Sub cmdPrint_Click()
With CrystalReport1
Dim sql As String
sql = "select CustomerID, CompanyName, ContactName, ContactTitle, " & _
"Address from Customers where Country = '" & cmbCountry.Text & "'"
Set rs = con.Execute(sql)
.ReportFileName = App.Path & "/RptTest.rpt"
.Destination = crptToWindow
.SetTablePrivateData 0, 3, rs
.WindowState = crptMaximized
.WindowShowPrintBtn = True
.Action = 1
End With
End Sub
5. And the report looks like this.
That's all folks.