Click here to Skip to main content
Click here to Skip to main content
Go to top

How to Load and Display Crystal Reports in VB.NET

, 6 Mar 2005
Rate this:
Please Sign up or sign in to vote.
An article about how to load and display Crystal Reports and handle the parameters and logon information.

Introduction

The following code shows how to load Crystal Reports in VB.NET, solving all the issues of logon, including sub reports and parameter passing. You can view your reports by simply calling the required functions with its parameters.

Using the Code

Using this code in your application is very simple. In the first step you need to add a form, and name it frmViewReport, then place the Crystal Report Viewer control on the form and name it rptViewer. In the code section, simply paste the following function. You can call this function from anywhere in your application with reference to the frmViewReport form. The sample code for calling the function is given below:

Dim objForm As New frmViewReport
objForm.ViewReport("C:\test.rtp", , "@parameter1=test¶mter2=10")
objForm.show()

Now let me explain you in detail what is going on in the code and what the format of the parameter string is. If there are parameters in the Crystal Reports then they should be passed with their values to the param of the function. The parameter string should be in the following format:

<First Parameter Name>=<First Paramter Value>&
<Second Parameter Name>=<Second Paramter Value>..

Note the parameter name and its value pairs are separated by an '&'. The report name with its full path should be passed to sReportName function.

Following is the function code with comments. I hope there will be no problem in understanding the code. Even if there is anything bothering you then drop me a message I'll explain that:

Friend Function ViewReport(ByVal sReportName As String, _
    Optional ByVal sSelectionFormula As String = "", _
    Optional ByVal param As String = "") As Boolean

    'Declaring variablesables
    Dim intCounter As Integer
    Dim intCounter1 As Integer

    'Crystal Report's report document object
    Dim objReport As New _
        CrystalDecisions.CrystalReports.Engine.ReportDocument 

    'object of table Log on info of Crystal report
    Dim ConInfo As New CrystalDecisions.Shared.TableLogOnInfo

    'Parameter value object of crystal report 
    ' parameters used for adding the value to parameter.
    Dim paraValue As New CrystalDecisions.Shared.ParameterDiscreteValue

    'Current parameter value object(collection) of crystal report parameters.
    Dim currValue As CrystalDecisions.Shared.ParameterValues

    'Sub report object of crystal report.
    Dim mySubReportObject As _
        CrystalDecisions.CrystalReports.Engine.SubreportObject

    'Sub report document of crystal report.
    Dim mySubRepDoc As New _
        CrystalDecisions.CrystalReports.Engine.ReportDocument

    Dim strParValPair() As String
    Dim strVal() As String
    Dim index As Integer

    Try

        'Load the report
        objReport.Load(sReportName)

        'Check if there are parameters or not in report.
        intCounter = objReport.DataDefinition.ParameterFields.Count

        'As parameter fields collection also picks the selection 
        ' formula which is not the parameter
        ' so if total parameter count is 1 then we check whether 
        ' its a parameter or selection formula.

        If intCounter = 1 Then
            If InStr(objReport.DataDefinition.ParameterFields(_
                0).ParameterFieldName, ".", CompareMethod.Text) > 0 Then
                intCounter = 0
            End If    
        End If

        'If there are parameters in report and 
        'user has passed them then split the 
        'parameter string and Apply the values 
        'to their concurrent parameters.

        If intCounter > 0 And Trim(param) <> "" Then
            strParValPair = param.Split("&")

            For index = 0 To UBound(strParValPair)
            If InStr(strParValPair(index), "=") > 0 Then
                strVal = strParValPair(index).Split("=")
                paraValue.Value = strVal(1)
                currValue = _ 
                    objReport.DataDefinition.ParameterFields(_
                    strVal(0)).CurrentValues
                currValue.Add(paraValue)
                objReport.DataDefinition.ParameterFields(_
                    strVal(0)).ApplyCurrentValues(currValue)
            End If
        Next
    End If

    'Set the connection information to ConInfo 
    'object so that we can apply the 
    'connection information on each table in the report
    ConInfo.ConnectionInfo.UserID = <User Name>
    ConInfo.ConnectionInfo.Password = <Password>
    ConInfo.ConnectionInfo.ServerName = <Server Name>
    ConInfo.ConnectionInfo.DatabaseName = <Database Name>

    For intCounter = 0 To objReport.Database.Tables.Count - 1
        objReport.Database.Tables(intCounter).ApplyLogOnInfo(ConInfo)
    Next

    ' Loop through each section on the report then look 
    ' through each object in the section
    ' if the object is a subreport, then apply logon info 
    ' on each table of that sub report

        For index = 0 To objReport.ReportDefinition.Sections.Count - 1
            For intCounter = 0 To _
                objReport.ReportDefinition.Sections(_
                index).ReportObjects.Count - 1
            With objReport.ReportDefinition.Sections(index)
                If .ReportObjects(intCounter).Kind = _
                CrystalDecisions.Shared.ReportObjectKind.SubreportObject Then
                    mySubReportObject = CType(.ReportObjects(intCounter), _
                      CrystalDecisions.CrystalReports.Engine.SubreportObject)
                    mySubRepDoc = _ 
             mySubReportObject.OpenSubreport(mySubReportObject.SubreportName)
                 For intCounter1 = 0 To mySubRepDoc.Database.Tables.Count - 1
                       mySubRepDoc.Database.Tables(_
                           intCounter1).ApplyLogOnInfo(_
                           ConInfo)sp;
                       mySubRepDoc.Database.Tables(_
                           intCounter1).ApplyLogOnInfo(ConInfo)
                 Next
                 End If
             End With
         Next
     Next
    'If there is a selection formula passed to this function then use that
    If sSelectionFormula.Length > 0 Then
        objReport.RecordSelectionFormula = sSelectionFormula
    End If
    'Re setting control 
    rptViewer.ReportSource = Nothing

    'Set the current report object to report.
    rptViewer.ReportSource = objReport

    'Show the report
    rptViewer.Show()
        Return True
    Catch ex As System.Exception
        MsgBox(ex.Message)
    End Try
End Function

Points of Interest

The main problems while developing the function were the sub reports and the selection formula. When there were no parameters and only the selection formula, the function failed because the parameters collection was picking the selection formula. Initially it was hard to detect, but finally I solved that problem.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Danish Alam

Pakistan Pakistan
No Biography provided

Comments and Discussions

 
QuestionThis Code is working fine but there is a little bit problem PinmemberSHERAZ SHIEKH30-Jul-14 14:31 
QuestionUnderstanding PinmemberScott J Smith21-Dec-12 8:54 
QuestionExcellent coding and some suggestions PinmemberAmila thennakoon9-Oct-11 22:56 
GeneralMy vote of 5 PinmemberKen LeBlanc2-Jun-11 10:22 
GeneralParameters to a SubReport Pinmemberricky99022-May-11 20:49 
Generaldata not displayed in crytsal report Pinmembersvknair19-May-11 20:10 
GeneralUsing crystal report 8.5 in vb.net Pinmemberrocky cardinal11-Apr-11 18:26 
Generalusing similar code but still getting error values cannot be NUll Pinmembersvknair1-Feb-11 22:05 
Generalneed help with .net and crystal report PinmemberAltafAli4-Dec-10 15:34 
GeneralRe: need help with .net and crystal report Pinmembermoses_gandhar27-Feb-11 22:27 
GeneralMy vote of 2 PinmemberMember 44736092-Dec-10 23:22 
Questionparameter in subreport Pinmemberkankmonty25-Oct-10 18:19 
QuestionCR 8.5 and VB Express 2010 Pinmemberwaseemsz28-Jun-10 9:31 
GeneralRequest for Code Update to VB 2008/2010 Please PinmemberBilal Dadar24-May-10 3:58 
GeneralExcellent code and explanation thank you for the time and effort of providing the code Pinmembercmaster8-Apr-10 3:44 
GeneralQuestions about your example. PinmemberJohn Heck17-Aug-09 3:04 
GeneralDoesn't work PinmemberNickspi12-Jun-09 7:47 
QuestionMulti Table PinmemberDawit Kiros7-Apr-09 9:25 
Generalcr 8.5 & VB 2008 Express Pinmemberananthaas19-Mar-09 1:41 
QuestionHow to read Print dialog of frmviewreport Pinmemberbunary2k19-Feb-09 21:48 
Questionabout creating crystal report in vb.net Pinmembernavsar28-Jan-09 0:02 
GeneralAbout crystal reports PinmemberMr. Milton30-Oct-08 23:59 
GeneralRe: About crystal reports PinmemberTareqdhk10-Mar-10 19:23 
Generalcrystal report report Pinmemberprakash_adysoft11-Sep-08 4:52 
GeneralRe: crystal report report PinmemberAmila thennakoon9-Oct-11 23:06 
QuestionHow to pass parameters in Crystal Report PinmemberAshvin Johnson11-Sep-08 4:05 
GeneralParameters not set PinmemberJerryElbow4-Sep-08 8:48 
GeneralLicense Question Pinmemberthumb2216-Apr-08 10:53 
GeneralExcellent!!! PinmemberJShow15-Apr-08 6:16 
GeneralRe: Excellent!!! Pinmemberedwarmartinez13-Aug-08 15:34 
GeneralCrystal Report Download PinmemberDennisKeeling21-Nov-07 2:26 
GeneralParameter value not set [modified] PinmemberMuhammad Shafiq16-Nov-07 3:57 
GeneralConfirmed, this sample does not work [modified] PinmemberAliasGoesHere5-Nov-07 7:14 
GeneralRe: Confirmed, this sample does not work PinmemberAliasGoesHere21-Nov-07 11:00 
GeneralRe: Confirmed, this sample does not work PinmemberBruceL14-Mar-08 9:08 
GeneralRe: Confirmed, this sample does not work - Fix for BADINDEX Error PinmemberBruceL14-Mar-08 9:35 
GeneralRe: Confirmed, this sample does not work - Fix for BADINDEX Error Pinmembernfalk9-Jun-09 3:54 
GeneralRe: Confirmed, this sample does not work PinmemberHeinD23-Mar-09 10:01 
GeneralRe: Confirmed, this sample does not work - Another way to fix this PinmemberJeanjeanot4-May-09 1:27 
GeneralRe: Confirmed, this sample does not work - Another way to fix this PinmemberRene Samuel11-May-09 17:28 
QuestionThe Crystal Report Viewer control Pinmembersnakewine17-Oct-07 11:59 
QuestionLoad report from repository? PinmemberBrichowski4-Sep-07 0:00 
GeneralCrystal Report and VB Express Edition PinmembertutzkiE1-Sep-07 2:43 
GeneralGood but not display any data PinmemberHetkeval12-Aug-07 12:34 
QuestionParamater Error PinmemberMackiaRSA8-Aug-07 20:52 
Generalnotes on VB Pinmembermpyanap16-Jul-07 5:55 
Generalexcellent code Pinmemberria1712-Jul-07 20:04 
Generalexcellnt code Pinmemberria1729-Jun-07 1:22 
Questioncrystal report in vb.net Pinmemberria1728-Jun-07 20:28 
AnswerRe: crystal report in vb.net Pinmembersnakewine18-Oct-07 4:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140926.1 | Last Updated 6 Mar 2005
Article Copyright 2005 by Danish Alam
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid