Click here to Skip to main content
11,720,374 members (79,896 online)
Click here to Skip to main content

Displaying , Exporting and Printing Crystal Reports in ASP.NET

, 14 Mar 2005 CPOL 395.6K 12K 101
Rate this:
Please Sign up or sign in to vote.
Displaying , exporting and printing crystal reports in ASP.NET with source code.

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:

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:

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

Or can also be used as:

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

License

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

Share

About the Author

patelsachin
Web Developer
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
Questiona problem export word, rtf! Pin
Member 117541529-Jun-15 12:24
memberMember 117541529-Jun-15 12:24 
GeneralMy vote of 1 Pin
kashishkhanna5-Nov-14 23:53
memberkashishkhanna5-Nov-14 23:53 
Questionprint report in c# Pin
Mohammed Abdul Muqeet20-Jan-13 0:33
memberMohammed Abdul Muqeet20-Jan-13 0:33 
Questionprinttoprinter Error Pin
er_ashu18-Jul-12 0:40
memberer_ashu18-Jul-12 0:40 
GeneralMy vote of 3 Pin
parthmehta.indianic17-Mar-12 0:02
memberparthmehta.indianic17-Mar-12 0:02 
QuestionExport excel with password protected Pin
selvakumark19-Feb-12 16:27
memberselvakumark19-Feb-12 16:27 
Questionexport crystal report into pdf from 2nd page Pin
selvakumark16-Feb-12 15:58
memberselvakumark16-Feb-12 15:58 
hi, using c#, itext how to export crystal report from 2nd page onwards?

below is my code for exporting all pages

ReportDocument objRDoc = new ReportDocument();
objRDoc.Load("rpt path");
ExportOptions expo = objRDoc.ExportOptions;
expo.ExportDestinationType = ExportDestinationType.DiskFile;
expo.ExportFormatType = ExportFormatType.PortableDocFormat;
DiskFileDestinationOptions objDfDopt.DiskFileName = "pdf path";
expo.DestinationOptions = objDfDopt;
objRDoc.Export();
objRDoc.Refresh();

modified 16-Feb-12 22:13pm.

GeneralMy vote of 5 Pin
manoj kumar choubey9-Feb-12 3:06
membermanoj kumar choubey9-Feb-12 3:06 
GeneralMy vote of 2 Pin
Member 42938943-Apr-11 18:16
memberMember 42938943-Apr-11 18:16 
GeneralCrystal Report viewer Pin
amitrajahuja11-Dec-10 3:25
memberamitrajahuja11-Dec-10 3:25 
GeneralAnother method Pin
Alexandru Matei12-Oct-09 2:55
memberAlexandru Matei12-Oct-09 2:55 
GeneralRe: Another method Pin
mahi159021-Mar-13 21:10
membermahi159021-Mar-13 21:10 
QuestionPrinting using Crystal reports Print Control Pin
KrutiCh30-Sep-08 6:45
memberKrutiCh30-Sep-08 6:45 
GeneralTroubles with Login Pin
Member 477445510-Sep-08 7:53
memberMember 477445510-Sep-08 7:53 
GeneralTrying in c# and gives an error Pin
mundaves8-Jul-08 13:42
membermundaves8-Jul-08 13:42 
GeneralProblem in export to excel with paramater Pin
shms3-Mar-08 16:06
membershms3-Mar-08 16:06 
Generalstill getting error Pin
patel heena d29-Jun-07 13:24
memberpatel heena d29-Jun-07 13:24 
Questionhow to create an object of crystal file Pin
patel heena d29-Jun-07 12:48
memberpatel heena d29-Jun-07 12:48 
GeneralWeb application doesn't show the report. Pin
m3n5413-Mar-07 16:30
memberm3n5413-Mar-07 16:30 
Generalgood one Pin
Member #26788916-Mar-07 19:09
memberMember #26788916-Mar-07 19:09 
Questioncrystal report Pin
kk_upadhyay28-Feb-07 22:15
memberkk_upadhyay28-Feb-07 22:15 
QuestionI am getting a record per page... Pin
grigorythegreat5-Feb-07 3:47
membergrigorythegreat5-Feb-07 3:47 
AnswerRe: I am getting a record per page... Pin
sylvesterg15-Feb-07 20:09
membersylvesterg15-Feb-07 20:09 
GeneralGood Artical Pin
sumja17-Jan-07 2:20
membersumja17-Jan-07 2:20 
Generalprinting error Pin
contact_ashishjain15-Nov-06 23:57
membercontact_ashishjain15-Nov-06 23:57 
GeneralRe: printing error Pin
backSlashZero12-Sep-07 20:46
memberbackSlashZero12-Sep-07 20:46 
QuestionURGENT : Crystal reports - export to prn programmatically Pin
NosheenA13-Nov-06 1:15
memberNosheenA13-Nov-06 1:15 
GeneralGood Example Pin
anil0012327-Sep-06 0:28
memberanil0012327-Sep-06 0:28 
GeneralThread was being aborted Pin
marquito_cuba5-Jun-06 11:50
membermarquito_cuba5-Jun-06 11:50 
GeneralGetting Blank Screen After Exporting PDF Pin
Sakkaravarthi10-May-06 0:08
memberSakkaravarthi10-May-06 0:08 
QuestionRe: Getting Blank Screen After Exporting PDF Pin
guyvds200025-Apr-07 2:45
memberguyvds200025-Apr-07 2:45 
GeneralRe: Getting Blank Screen After Exporting PDF Pin
hkdhamija19-Jul-07 0:12
memberhkdhamija19-Jul-07 0:12 
Generalexporting the report Pin
j0ms9-May-06 6:15
memberj0ms9-May-06 6:15 
Question"Logon Failed" error while printing crystal report Pin
Naynesh8-May-06 22:57
memberNaynesh8-May-06 22:57 
AnswerRe: "Logon Failed" error while printing crystal report Pin
tawpuia4-Jul-08 1:24
membertawpuia4-Jul-08 1:24 
JokeGood Artical Pin
ykg1-May-06 1:39
memberykg1-May-06 1:39 
GeneralRe: Good Artical Pin
Suresh Dayma7-Sep-06 6:35
memberSuresh Dayma7-Sep-06 6:35 
GeneralError export Report with parameters Pin
Don Maxim28-Feb-06 22:18
memberDon Maxim28-Feb-06 22:18 
GeneralRe: Error export Report with parameters Pin
Thanh-hdu5-Mar-07 21:53
memberThanh-hdu5-Mar-07 21:53 
GeneralUnable to debug the application Pin
skan81228-Feb-06 1:09
memberskan81228-Feb-06 1:09 
GeneralRe: Unable to debug the application Pin
Sakkaravarthi10-May-06 0:09
memberSakkaravarthi10-May-06 0:09 
GeneralLogon Failed with C# web application Pin
quocviet47717-Jan-06 16:25
memberquocviet47717-Jan-06 16:25 
Generalcrsytal report login failure Pin
vipindev27-Dec-05 1:21
membervipindev27-Dec-05 1:21 
QuestionHow could I use share printer for to print? Pin
Agent00931-Oct-05 20:21
memberAgent00931-Oct-05 20:21 
QuestionProblem to export to MS Word Pin
lopez.carlos@inet.com.sv13-Oct-05 6:21
susslopez.carlos@inet.com.sv13-Oct-05 6:21 
AnswerRe: Problem to export to MS Word Pin
Gerald Lee26-Jan-06 14:23
memberGerald Lee26-Jan-06 14:23 
GeneralRe: Problem to export to MS Word Pin
Thanh-hdu5-Mar-07 20:01
memberThanh-hdu5-Mar-07 20:01 
GeneralRe: Problem to export to MS Word Pin
Thanh-hdu5-Mar-07 20:23
memberThanh-hdu5-Mar-07 20:23 
GeneralAnother Logon Failure Pin
Lilay8-Oct-05 8:07
memberLilay8-Oct-05 8:07 
GeneralRe: Another Logon Failure Pin
sudheerbalanagu18-Dec-05 20:10
membersudheerbalanagu18-Dec-05 20:10 

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 | Terms of Use | Mobile
Web02 | 2.8.150901.1 | Last Updated 15 Mar 2005
Article Copyright 2005 by patelsachin
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid