Click here to Skip to main content
15,881,172 members
Articles / Web Development / ASP.NET
Article

Displaying , Exporting and Printing Crystal Reports in ASP.NET

Rate me:
Please Sign up or sign in to vote.
3.36/5 (43 votes)
14 Mar 2005CPOL1 min read 511.2K   13.3K   101   78
Displaying , exporting and printing crystal reports in ASP.NET with source code.

Image 1

Introduction

The main purpose of this document is to display the report without any error. I was bugged by the "Logon Failed Error" for several days, and now I finally have a code that displays report without any error. The code also Exports the report into .pdf, .xls, .rtf and .doc formats. It also prints the report directly to the printer.

Using the code

Unzip the crCodes.Zip and then run the crCode.vbproj project file.

--- OR ----

Just insert the Webform1.aspx file into your existing project, then copy the crystalreport2.rpt file into your project, and start using the code.

The entire source code of Webform1.aspx.vb is as follows. Simply design the form as shown in the image and place the Crystal Report Viewer control, and leave the name of controls to default:

VB
Imports CrystalDecisions.Shared
Imports System.IO

Public Class WebForm1
    Inherits System.Web.UI.Page

    Dim crReportDocument As CrystalReport2 = New CrystalReport2

    Protected WithEvents DropDownList1 As System.Web.UI.WebControls.DropDownList
    Protected WithEvents Button1 As System.Web.UI.WebControls.Button
    Protected WithEvents Label1 As System.Web.UI.WebControls.Label
    Protected WithEvents CrystalReportViewer1 As _
                             CrystalDecisions.Web.CrystalReportViewer
    Protected WithEvents Button2 As System.Web.UI.WebControls.Button

#Region " Web Form Designer Generated Code "
    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> 
    Private Sub InitializeComponent()

    End Sub

    'NOTE: The following placeholder declaration is required 
    'by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object,_ 
                        ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()


        ' this is the most IMPORTANT line of code
        ' if this line is not writen the 
        ' " LOGON FAILED" error starts displaying
        crReportDocument.SetDatabaseLogon("username",_ 
                                    "password", "sql-server", "database")

        ' the Above line works even if only username 
        ' and password is supplied as below

        'crReportDocument.SetDatabaseLogon("username",_
                                 "password") ', "sql-server", "database")

        ' this will hide the group tree
        CrystalReportViewer1.DisplayGroupTree = False

        CrystalReportViewer1.ReportSource = crReportDocument

        ' IF REPORT Uses Parameter's
        ' Pass Paramaters As Follows
        crReportDocument.SetParameterValue("city", "Mumbai")


        ' city = Parameter Name
        ' Mumbai = Parameter Value

        ' :-) thats ALL your Report Will Be displayed 
        ' now Without Logon Failed Error

        With DropDownList1.Items
            .Add("Rich Text (RTF)")
            .Add("Portable Document (PDF)")
            .Add("MS Word (DOC)")
            .Add("MS Excel (XLS)")
        End With
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object,_ 
                ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
    End Sub

    Sub ExportReport()

        Dim oStream As New MemoryStream ' // using System.IO

        'this contains the value of the selected export format.
        Select Case DropDownList1.SelectedItem.Text 

            Case "Rich Text (RTF)"
                '-----------------------------------------------------------

                oStream = crReportDocument.ExportToStream(_
                    CrystalDecisions.Shared.ExportFormatType.WordForWindows)
                Response.Clear()
                Response.Buffer = True
                Response.ContentType = "application/rtf"
                '------------------------------------------------------------

                '------------------------------------------------------------
            Case "Portable Document (PDF)"

                oStream = crReportDocument.ExportToStream(_
                    CrystalDecisions.Shared.ExportFormatType.PortableDocFormat)
                Response.Clear()
                Response.Buffer = True
                Response.ContentType = "application/pdf"
                '--------------------------------------------------------------

                '--------------------------------------------------------------
            Case "MS Word (DOC)"

                oStream = crReportDocument.ExportToStream(_
                        CrystalDecisions.Shared.ExportFormatType.WordForWindows)
                Response.Clear()
                Response.Buffer = True
                Response.ContentType = "application/doc"
                '---------------------------------------------------------------

                '---------------------------------------------------------------
            Case "MS Excel (XLS)"

                oStream = crReportDocument.ExportToStream(_
                                 CrystalDecisions.Shared.ExportFormatType.Excel)
                Response.Clear()
                Response.Buffer = True
                Response.ContentType = "application/vnd.ms-excel"
                '---------------------------------------------------------------
        End Select 'export format
        Try
            Response.BinaryWrite(oStream.ToArray())
            Response.End()
        Catch err As Exception
            Response.Write("< BR >")
            Response.Write(err.Message.ToString)
        End Try
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) Handles Button2.Click
        ExportReport()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) Handles Button1.Click
        crReportDocument.SetDatabaseLogon("USER", _
                                "PASSWORD", "SQL-SERVER", "DATABASE")
        crReportDocument.PrintToPrinter(1, False, 0, 0)
    End Sub
End Class

Why is the "Logon Failed Error" generated

The "Logon Failed" error is generated basically because, when the report is being displayed it tries to log on to the database server. Even though you have selected the server while designing, the report still needs the server name while displaying or exporting or printing.

The code line that removes the error is:

VB
crReportDocument.SetDatabaseLogon("USER", "PASSWORD", "SQL-SERVER", "DATABASE")

Or can also be used as:

VB
crReportDocument.SetDatabaseLogon("USER", "PASSWORD")

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow to refresh data when Report export DPF file Pin
cuongeagle26-Sep-05 21:41
cuongeagle26-Sep-05 21:41 
Generalprinting and exporting error Pin
Member 239228726-Jul-05 20:17
Member 239228726-Jul-05 20:17 
GeneralRe: printing and exporting error Pin
gurumosch29-Jul-05 1:02
gurumosch29-Jul-05 1:02 
Generalprinting error Pin
Anonymous26-Jul-05 20:12
Anonymous26-Jul-05 20:12 
GeneralRe: printing error Pin
Suresh Pirsquare7-Sep-06 6:43
Suresh Pirsquare7-Sep-06 6:43 
GeneralShow report for from searching Pin
Nisarat2-Jun-05 23:12
Nisarat2-Jun-05 23:12 
GeneralRe: Show report for from searching Pin
pityangel200628-May-06 18:40
pityangel200628-May-06 18:40 
GeneralSource Pin
Anonymous27-May-05 7:03
Anonymous27-May-05 7:03 
GeneralLogInFailed Pin
Anonymous27-May-05 6:56
Anonymous27-May-05 6:56 
GeneralRe: LogInFailed Pin
patelsachin27-May-05 18:47
patelsachin27-May-05 18:47 
GeneralRe: LogInFailed Pin
Aubyone23-Nov-05 19:06
Aubyone23-Nov-05 19:06 
GeneralPrinting Problems Pin
Amorous10-May-05 3:28
Amorous10-May-05 3:28 
GeneralRe: Printing Problems Pin
nikhiljain18-May-05 2:03
nikhiljain18-May-05 2:03 
GeneralRe: Printing Problems Pin
Member 314926121-Jun-05 7:31
Member 314926121-Jun-05 7:31 
QuestionHow export to txt Pin
Moises Acevedo2-May-05 10:04
sussMoises Acevedo2-May-05 10:04 
AnswerRe: How export to txt Pin
selvakumark16-Feb-12 16:46
selvakumark16-Feb-12 16:46 
Generalhelp: exported long list of wording on the screen Pin
suki_icy27-Apr-05 23:43
susssuki_icy27-Apr-05 23:43 
GeneralRe: help: exported long list of wording on the screen Pin
patelsachin29-Apr-05 19:13
patelsachin29-Apr-05 19:13 
GeneralRe: help: exported long list of wording on the screen Pin
suki_icy2-May-05 14:32
susssuki_icy2-May-05 14:32 
GeneralTHX works for me Pin
esman225-Mar-05 20:35
esman225-Mar-05 20:35 
GeneralExportToStream not a member Pin
codispdp25-Mar-05 7:57
codispdp25-Mar-05 7:57 
GeneralParms Pin
Angjbs24-Mar-05 6:21
Angjbs24-Mar-05 6:21 
GeneralRe: Parms Pin
patelsachin27-Mar-05 20:20
patelsachin27-Mar-05 20:20 
GeneralRe: Parms Pin
anthnguy827-May-06 20:12
anthnguy827-May-06 20:12 
GeneralLogon failed Pin
albatros41519-Mar-05 23:30
albatros41519-Mar-05 23:30 

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

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