How to Run Crystal Report using Crystal Report Viewer in VS.NET

Following example developed in Visual Studio.NET 2005. In the following code we will see that how to use crystal report viewer in .NET.

 

Steps to use the crystal report viewer:-

 

Import the following namespace for sql server configuration settings.

 

Imports System.Data.SqlClient 

'Code to configure the database settings

'Change the server="your server name where your sql server is running"

'database="Default" database "pubs" and sql "userid" and the "password"

    Dim strConnection As String = "server=dtpxp-skumari;database=pubs;uid=sa;pwd=;"

    Dim Connection As New SqlConnection(strConnection)

    Dim strSQL As String = "Select * From authors"

    Dim DA As New SqlDataAdapter(strSQL, Connection)

    Dim DS As New DataSet

'Variable to assign the report name

    Dim strReportName As String 

 

Next we are going to add the .rpt(Report)file. Right click on

 

The Project solution --> Add --> New Item --> .rpt File

 

It will open the following window. Select the Report wizard.
 

run-Crystal-Report.jpg

 

Specifying the data --> Create new connection --> OLEDB(ADO) --> specify the data provider by following screen.

 

Create-new-connection.jpg
 

 

Go next till the last screen. Select the style of report.

 

Now, after creating the .rpt file we need to write the code to fill the data source.

 

Create a datatable in your dataset. The datatable's name

 

        DA.Fill(DS)

        'Pass the reportname to string variable

        strReportName = "CrystalReport2"

 

        'Get the Report Location

        Dim strReportPath As String = Application.StartupPath & "\" & strReportName & ".rpt"

        'Check file exists

        If Not IO.File.Exists(strReportPath) Then

            Throw (New Exception("Unable to locate report file:" & vbCrLf & strReportPath))

        End If

 

        'Assign the datasource and set the properties for Report viewer

        Dim rptDocument As New CrystalDecisions.CrystalReports.Engine.ReportDocument

 

        rptDocument.Load(strReportPath)

        rptDocument.SetDataSource(DS.Tables(0))

        rptViewer.ShowRefreshButton = False

        rptViewer.ShowCloseButton = False

        rptViewer.ShowGroupTreeButton = False

        rptViewer.ReportSource = rptDocument


Similar Articles