It is very easy to use a crystal report in VB. You only need to use a crystal report to create a report and directly call it in VB. However, to dynamically bind a crystal report to a database, make some modifications.
1. Add a crystal report to the vb project.
Right-click "Project Resource Manager", select "add...", select "Crystal report 9" in the pop-up menu, and add a report and a form form2 by default.
2. Set the crystal report. (Author: Li dongchao)
Double-click "crystalreport1" to open the crystal report editor. Right-click "database Field" and select "database expert... ", open the" Database Expert "window, click" Create New Connection ", select" field definition only ", open the" field definition only "window, and click" Create File... ", fill in the content in" database definition tool "(the Field name here must be the same as the field name to be displayed in the report). After adding it, the" save "dialog box will pop up and enter the file name, save a ". TTX file. This. TTX file is actually a text file. One line represents a field. The format of each line is: field name + {tab} + Type + {tab} + length. For example:
GP string 30
CDM string 20
QX string 10
After saving, return to the crystal report editor and drag the fields you want to your report.
3. Add a module1 module and define two public variables:
Public connection as new ADODB. Connection
Public rec as new ADODB. recordset
4. Content in the form2 form (Author: Li dongchao)
Private sub form_load ()
Dim SQL
Dim apppath as string 'sets the PATH variable
Dim dB as string
Apppath = app. path' get the program path
If right (apppath, 1) <> "/" then apppath = apppath + "/"
'If no "/" is at the end of the path, add it
'Combined with relative paths to form absolute paths
DB = apppath + "db1.mdb"
If connection. State = adstateopen then
Else
Connection. cursorlocation = aduseclient
Connection. Open "provider = Microsoft. Jet. oledb.4.0; Data Source =" + dB + "; persist Security info = false"
End if
Rec. cursorlocation = aduseclient
SQL = "select groupname as GP, CDM, QX from userqxtable"
Rec. Open SQL, connection, 1, 1
Screen. mousepointer = vbhourglass
Crviewer91.reportsource = crystalreport1
Crystalreport1.database. setdatasource rec binds the database to the Crystal Report (Author: Li dongchao)
Crystalreport1.text2. settext "your report title" 'dynamically change the title
Crystalreport1.unboundstring1. setunboundfieldsource "{1.gp}" 'Use unbound Fields
Crystalreport1.readrecords
Crviewer91.viewreport
Screen. mousepointer = vbdefault
End sub