Programming Crystal Reports With ASP
Programming Crystal Reports With ASP
Programming Crystal Reports With ASP
(Page 4 of 6 )
To solve this problem, we can provide database logon information to the CrystalReportViewer
control dynamically at runtime. The following is the code to achieve the same:
Imports CrystalDecisions.Shared
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles form1.Load
Dim ConnInfo As New ConnectionInfo
With ConnInfo
.ServerName = ".sqlexpress"
.DatabaseName = "Northwind"
.UserID = "sa"
.Password = "eXpress2005"
End With
For Each cnInfo As TableLogOnInfo In Me.CrystalReportViewer1.LogOnInfo
cnInfo.ConnectionInfo = ConnInfo
Next
End Sub
End Class
You must observe that the CrystalDecisions.Shared namespace is added to the top. In the above
code, the database connection information is stored in ConnInfo and is defined as follows:
The above connection information is assigned to CrystalReportViewer control using the following
code:
Programming Crystal Reports with ASP.NET 2.0 - Hiding the toolbar and adding First,
Last, Next and Previous page buttons to the report
(Page 5 of 6 )
By default, CrystalReportViewer automatically displays toolbar at the top. Not every end user uses
all features. At the same time, some end users may not like the toolbar.
To hide the toolbar, modify the CrystalReportViewer code (in Source mode) as follows:
Add First, Last, Next and Previous page buttons to the web page and modify the code behind with
new events as follows:
Programming Crystal Reports with ASP.NET 2.0 - Enhancing the report with run-time
binding along with session handling
(Page 6 of 6 )
In all of the above sections, the CrystalReportViewer worked with CrystalReportSource. Now, let us
dynamically add a report source to the CrystalReportViewer and bind it at runtime. This gives us the
flexibility to use the same viewer for different reports (showing one at a time).
Add a new web page to the project, add the four buttons (First, Previous, Next and Last) and a
CrystalReportViewer control. Modify the CrystalReportViewer control, so that it looks like the
following:
Imports CrystalDecisions.Shared
Imports CrystalDecisions.CrystalReports.Engine
Add the following code to bind the report for every button click and also during the page load event:
I hope you enjoyed the article and any suggestions, bugs, errors, enhancements etc. are highly
appreciated at http://jagchat.spaces.live.com
Crystal Reports is the standard reporting tool for Visual Studio .NET used to display
data of presentation quality. You can display multiple-level totals, charts to analyze
data, and much more in Crystal Reports. Creating a Crystal Report requires minimal
coding since it is created in Designer interface. It is available as an integrated
feature of Microsoft Visual Studio .NET, Borland Delphi, and C#Builder.
1. Rapid report development since the designer interface would ease the coding work
for the programmer.
2. Can extend it to complicated reports with interactive charts and enhance the
understanding of the business model
3. Exposes a report object model, can interact with other controls on the ASP.NET
Web form
4. Can programmatically export the reports into widely used formats like .pdf,
.doc, .xls, .html and .rtf
Implementation Models
Crystal Reports need database drivers to connect to the data source for accessing
data. Crystal Reports in .net support two methods to access data from a data source:
Strongly-typed Report
When you add a report file into the project, it becomes a "strongly-typed" report. In
this case, you will have the advantage of directly creating an instance of the report
object, which could reduce a few lines of code, and cache it to improve performance.
The related .vb file, which is hidden, can be viewed using the editor's "show all files"
icon in the Solution Explorer.
Un-Typed Report
Those reports that are not included into the project are "un-typed" reports. In this
case, you will have to create an instance of the Crystal Report Engine's
"ReportDocument" object and manually load the report into it.
We would use the following steps to implement Crystal Reports using the Pull Model:
1. Create the .rpt file (from scratch) and set the necessary database connections
using the Crystal Report Designer interface.
2. Place a CrystalReportViewer control from the toolbox on the .aspx page and
set its properties to point to the .rpt file that we created in the previous step.
2) On the "Crystal Report Gallery" pop up, select the "As a Blank Report" radio
button and click "ok".
3) This should open up the Report File in the Crystal Report Designer.
4) Right click on the "Details Section" of the report, and select "Database" ->
"Add/Remove Database".
5) In the "Database Expert" pop up window, expand the "OLE DB (ADO)" option by
clicking the "+" sign, which should bring up another "OLE DB (ADO)" pop up.
6) In the "OLE DB (ADO)" pop up, Select "Microsoft OLE DB Provider for SQL Server"
and click Next.
9) Now you should be able to see the Database Expert showing the table that have
been selected
10) Expand the "Pubs" database, expand the "Tables", select the "Stores" table and
click on ">" to include it into the "Selected Tables" section.
Note: If you add more than one table in the database Expert and the added tables
have matching fields, when you click the OK button after adding the tables, the links
between the added tables is displayed under the Links tab. You can remove the link
by clicking the Clear Links button.
11) Now the Field Explorer should show you the selected table and its fields under
the "Database Fields" section, in the left window.
12) Drag and drop the required fields into the "Details" section of the report. The
field names would automatically appear in the "Page Header" section of the report. If
you want to modify the header text then right click on the text of the "Page Header"
section, select "Edit Text Object" option and edit it.
2) Open the properties window for the Crystal Report Viewer control.
3) Click on the [...] next to the "Data Binding" Property and bring up the data
binding pop-up window
5) Select the "Custom Binding Expression" radio button, on the right side bottom of
the window and specify the sample .rpt filename and path as shown in the fig.
6) You should be able to see the Crystal Report Viewer showing you a preview of
actual report file using some dummy data and this completes the inserting of the
Crystal Report Viewer controls and setting its properties.
Note: In the previous example, the CrystalReportViewer control was able to directly
load the actual data during design time itself as the report was saved with the data.
In this case, it will not display the data during design time as it not saved with the
data - instead it will show up with dummy data during design time and will fetch the
proper data only at run time.
7) Call the Databind method on the Page Load Event of the Code Behind file
(.aspx.vb). Build and run your .aspx page. The output would look like this.
Using a PUSH model
1. Create a Dataset during design time.
2. Create the .rpt file (from scratch) and make it point to the Dataset that we
created in the previous step.
3. Place a CrystalReportViewer control on the .aspx page and set its properties to
point to the .rpt file that we created in the previous step.
4. In your code behind page, write the subroutine to make the connections to the
database and populate the dataset that we created previously in step one.
The .xsd file created this way contains only the field definitions without any data in
it. It is up to the developer to create the connection to the database, populate the
dataset and feed it to the Crystal Report.
5) After creating the .rpt file, right click on the "Details" section of the Report file,
select "Add/Remove Database"
6) In the "Database Expert" window, expand "Project Data" (instead of "OLE DB"
that was selected in the case of the PULL Model), expand "ADO.NET DataSet",
"DataSet1", and select the "Stores"table.
7) Include the "Stores" table into the "Selected Tables" section by clicking on ">"
and then Click "ok"
8) Follow the remaining steps to create the report layout as mentioned previously in
the PULL Model to complete the .rpt Report file creation
Code Behind Page Modifications: 10) Call this subroutine in your page load event:
Note: In the above code, you would notice that the object oRpt is an instance of the
"Strongly Typed" Report file. If we were to use an "UnTyped" Report then we would
have to use a ReportDocument object and manually load the report file into it.
1. Generate a dataset that contains data according to your selection criteria, say
"where (cost>1000)".
3. Right Click Group Name fields in the field Explorer window and select insert Group
from the shortcut menu. Select the relevant field name from the first list box as
shown.
The group name field is created, since the data needs to be grouped on the basis of
the cat id say.
4. A plus sign is added in front of Group Name Filed in the field explorer window. The
Group Name Field needs to be added to the Group Header section of the Crystal
Report. Notice this is done automatically.
5. Right Click the running total field and select new. Fill the required values through
> and the drop down list.
6. Since the count of number of categories is to be displayed for the total categories,
drag RTotal0 to the footer of the report.
Create a formula
Suppose if the report required some Calculations too. Perform the following steps:
1. Right Click the formula Fields in the field explorer window and select new. Enter
any relevant name, say percentage.
2. A formula can be created by using the three panes in the dialog box. The first
pane contains all the crystal report fields, the second contains all the functions, such
as Avg, Sin, Sum etc and the third contains operators such as arithmetic, conversion
and comparison operators.
3. Double click any relevant field name from the forst pane, say there's some field
like advance from some CustOrder table. Then expand Arithmetic from the third
pane and double click Divide operator.
4. Double click another field name from the first which you want to use as divisor of
the first field name already selected say it is CustOrder.Cost.
5. Double Click the Multiply from third pane and the type 100.
You can opt to export your report file into one of the following formats:
To accomplish this you could place a button on your page to trigger the export
functionality.
Introduction
This article explains how to use PUSH method for drawing reports. It will also explain how to use user
DataSets in an ASP.NET page for reports. There are two types of methods for drawing the reports:
1. PULL method- the crystal report makes connection with the database, brings
the fields data and draws the report.
2. PUSH method- we create the DataSet, choose fields of the DataSet as
report fields and then push it to the crystal report. Here I am going to explain
the PUSH method only.
Steps
1. Create a new ASP.NET project.
6. Then drag the fields from the database fields of server explorer in the detail
section of the report. Arrange the fields as you want.
From the toolbox, add crystal report viewer control on to the page. That will add this variable:
Points to be careful of
1. Give same names on Dataset and the table element name of inserted
DataSet.
2. As and when you modify DataSet, build it again and log off the current
connections in report. Set the DataSource location again pointing to new
DataSet, otherwise database fields of the report will not take the change.
3. Setting up DataBind properties of the report viewer can be avoided. It can
be done at runtime
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.
--- 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:
End Sub
'crReportDocument.SetDatabaseLogon("username",_
"password") ', "sql-server", "database")
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
Sub ExportReport()
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
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.
Abstract
One of the most common questions regarding Crystal Reports in ASP.NET is how to
automatically print a Crystal Report. Because the Internet is a stateless,
disconnected medium, automatic printing of a Crystal Report using Web Forms
cannot be accomplished as easily as when using Windows Forms. This article
examines two options for automatic printing of a Crystal Report using ASP.NET and
compares one alternative method where the user must initiate printing.
Article Contents:
Introduction
Using Server-Side ReportDocument.PrintToPrinter Method
Client Side JavaScript: window.Print
Export to PDF
Conclusion and References
Introduction
[ Back To Top ]
Unlike the Windows Forms CrystalReportViewer toolbar, the web-based
CrystalReportViewer toolbar does not include a print button. For reports that are
directly rendered as HTML, the user can simply use the browser's print button. For
reports rendered as PDF or Excel, the user can use the print functionality in either
the Acrobat Reader or Excel to print the report.
Most users can figure out how to print the report, but some still need a little help,
and in some cases, clients request this as part of their application specs. In this
article, we'll review two methods for automatically printing a Crystal Report using
the web-based CrystalReportViewer: the server side ReportDoucment.PrintToPrinter
method, and a small client-side JavaScript that uses the window.print method. We'll
also discuss rendering a report in PDF and allowing the user to print that document
as an alternative to the two other methods. Because of the disconnected nature of
web client applications, and security considerations, there isn't a perfect way to
make every web-based Crystal Report automatically print. But, under certain
conditions, we can provide this functionality in user-friendly ways.
Using Server-Side ReportDocument.PrintToPrinter Method
[ Back To Top ]
This server-based method is documented in the Visual Studio help files. Open the
Help Index, and enter PrintToPrinter in the "Look for:" box. The syntax for this
method is:
'Collated' in this context has nothing to do with database collation. Some advanced
printers (like copier/printers) will sort each document into its own shelf. Not every
printer supports this functionality, so check the printer dialog before setting to true.
To print the entire report, set startpage and endpage each to 0.
MyReport.PrintToPrinter(1,False,0,0)
One limitation of this method is that a printer name must be specified. You can set
the default printer at design time in the report, and you can change the printer
name at run time by setting the ReportDocument.PrintOptions.PrinterName property (the
PrintOptions are also where you can assign page margins, portrait/landscape, etc.).
Keep in mind that this method prints from the server itself, not from the client
machine. This means that any printer you wish to use must be accessible from the
server. You cannot print to a client's desktop printer using this method unless that
printer is shared on the network and mapped to the server.
If your LAN has networked printers, you can make some guesses as to which printer
to assign as the default in each report. For instance, if the Accounting Department
has a departmental printer, that would be a good choice to use for the default in an
accounting report. You can provide users the option to choose a networked printer
by enumerating the printers mapped to the server and populating a drop-down list.
The PrinterSettings.InstalledPrinters property returns a collection of installed printers, and
can be bound to a DropDownList as below.
DropDownList1.DataSource = System.Drawing.Printing.PrinterSettings.InstalledPrinters
DropDownList1.DataBind()
Again, since this code is executing on the server, this will only enumerate the
printers on the server mapped to the System user. If a printer does not appear in
the drop-down list, you need to ensure that it is properly mapped to the System
user (see below).
All printers and the .NET Framework need to be mapped to the System user in order
for this to work. This is not a trivial task to configure. Printers can be mapped to
the system account only by editing the registry, and since the Framework is mapped
to the System user, you may need to reassign security permissions on files and
folders. This process is outlined in the "Printing Web-Based Reports From the
Server" article in the VS .NET help files (look up "Crystal Reports, printing" in the VS
help index to link to the articles.) and also in Reference 3 (at the end of this
article). The process is a little too intricate to cover here (leave comments if help is
needed, and I can amend the article later).
Client Side JavaScript: window.Print
[ Back To Top ]
A second option you have uses the JavaScript window.Print method. Adding this
method to the onLoad event of the BODY tag will trigger the browser to print the
current page. Adding this method to a button.onClick event can also be done, just
make sure you are using a standard HTML button and not an ASP.NET button control
(if you do use an ASP.NET button control, you'll cause a postback, not execute the
JavaScript). In a future article, we'll look at adding a print button to a
custom CrystalReportViewer toolbar that uses this method to print a report.
The window.print method does cause a printer selection window to open. The user will
have a chance to select the printer they want to use and must click the "Print"
button to start printing. There is no way to disable the prompt with JavaScript, so
for Netscape and other browsers, users will have to see the dialog. However, in
some versions of Internet Explorer, a call to the ExecWB OLE method from a second
browser object can be used to circumvent the print dialog (note: spaces have been
added to OBJECT declarations to display the code properly in this article--you should
remove the spaces to use the code):
function PrintWindow(){
if (navigator.appName == "Microsoft Internet Explorer") {
var PrintCommand = '< O B J E C T ID="PrintCommandObject" WIDTH=0 HEIGHT=0 ';
PrintCommand += 'CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></O B J E C
T>';
document.body.insertAdjacentHTML('beforeEnd', PrintCommand);
PrintCommandObject.ExecWB(6, -1); PrintCommandObject.outerHTML = ""; }
else { window.print();} }
The ExecWB method requires IE 5.5 or higher to function. This script essentially
creates another browser object of size 0 at the end of the current page. This new
browser object then issues a print command without prompting the user.
A limitation of the window.Print method is that only the current window will print. In
order to print all pages, you must set the SeparatePages property of your
CrystalReportViewer to False when the report is rendered. For example:
CrystalReportViewer1.SeparatePages=False
CrystalReportViewer1.ReportSource=MyReport
Setting SeparatePages to False will cause the entire report to be shown in the current
window. The user will not have to page through the report, but a lot of scrolling
may be required. Page breaks will appear wherever the browser puts them--there is
no way to control where page breaks occur--and the browser may wrap the layout in
order for it to fit the printer page dimensions. Your formatting may be completely
lost using the window.Print method if your report is wider than the browser window.
The basic window.Print method also prints everything in the window, including
whatever form inputs you have added, and the CrystalReportViewer toolbar. If you
have set SeparatePages= False, you probably don't need the toolbar displayed.
If you do not have any other inputs or buttons on your report page, turning off the
toolbar may be all you need to do. If you did add inputs or other buttons, having
them show on the printout will not look very professional. To make the report
appear a little more professional, we can enclose the report output in a DIV (by
enclosing the CrystalReportViewer in a DIV or Panel) and then print just that DIV
using a JavaScript function that opens a new window and includes only the
information inside the DIV. In a future article, we'll look at "skinning" the toolbar so
you can have a toolbar and this printing functionality at the same time. The basic
code is shown below (source: Reference 2; note that spaces have been added in
some tag names for them to display in this article - you should remove the spaces
to use the code):
var gAutoPrint = true; // Flag for whether or not to automatically call the print
function
function printSpecial() {
if (document.getElementById != null) {
var html = '\n\n';
if (document.getElementsByTagName != null) {
var headTags = document.getElementsByTagName("head");
if (headTags.length > 0)
html += headTags[0].innerHTML;
}
html += '\n< / H E A D >\n< B O D Y>\n';
var printReadyElem = document.getElementById("printReady");
if (printReadyElem != null) {
html += printReadyElem.innerHTML; }
else {
alert("Could not find the printReady section in the HTML"); return; }
html += '\n</ B O D Y >\n</ H T M L >';
var printWin = window.open("","printSpecial");
printWin.document.open();
printWin.document.write(html);
printWin.document.close();
if (gAutoPrint) printWin.print();
}
else {
alert("Sorry, the print ready feature is only available in modern browsers.");
} }
If you want to get really fancy, you can combine the two methods so that a report
window will automatically open and print in IE browsers or open and prompt for
printing in non-IE browsers. The combined code is shown below and has been
tested in both IE 6.0 and FireFox 0.9 (note: spaces have been inserted into tag
names so code will display properly--you should remove the spaces to use the
code):
var gAutoPrint = true; // Flag for whether or not to automatically call the print
function
function printSpecial() {
if (document.getElementById != null) {
var html = '< H T M L >\n< H E A D >\n';
if (document.getElementsByTagName != null) {
var headTags = document.getElementsByTagName("head");
if (headTags.length > 0) html += headTags[0].innerHTML;
}
if (gAutoPrint) {
if (navigator.appName == "Microsoft Internet Explorer") {
html += '\n</ H E A D >\n<'
html += 'B O D Y onLoad="PrintCommandObject.ExecWB(6, -1);">\n';
}
else {
html += '\n</ H E A D >\n< B O D Y >\n';
} }
else {
html += '\n</ H E A D >\n< B O D Y >\n';
}
One downside to this option is that users must start the printing process
themselves, which does not solve the problem of minimizing user
interaction. Unfortunately, since a PDF is not a page rendered by the browser, none
of the JavaScript tricks above will work for us. There is no simple way to
automatically print an exported Crystal Report in PDF format.
Conclusion and References
[ Back To Top ]
If your report is fairly simple, you can use the client-side JavaScript window.Print
command and a little scripting magic to come up with a satisfactory solution.
Complex reports generated using the JavaScript window.Print may lose the formatting
you desired, and, in non-IE browsers, some user intervention is required to answer
the Printer Setup dialog.
Printing Crystal Reports is not a process that can be easily automated in a very
satisfactory manner. There is no single magic solution to fit every need; you will
need to see which option works best in each situation. Future versions of Crystal
Reports .NET may contain additional functionality, and there are additional tricks we
can use in Crystal Reports 10 that will be looked at in a future article.
A web developer may or may not be aware of crystal report in depth as compared to
desktop application developer.
Couple of months back I was suppose to access crystal reports in asp.net, but I
found many problems while working with crystal report using crystalreportviewer in
asp.net. I am writing this application for web-developers who want to access crystal
reports in asp.net by using multiple tables or views etc. This application might help
them and save their development time.
List of problems which I came across while accessing crystal reports in asp.net
Logon failure
Refer to following URL
http://support.businessobjects.com/library/kbase
/articles/c2010371.asp
DLL not found
On a development machine if crystal report is not installed then you might get
above error
Fail to render page
Basically there could be two possible ways for the solution
1. This error can occur due to the unsuppressed report header, removing
space between the header might solve the problem.
2. This error can be solved by assigning permission to ASPNET user by
default. ASPNET user does not have permission on windows XP and XP
professional machine. To explain in detail it creates crystal report
image in the local machine's temp directory or in the same directory
where application is residing, due to security issue or permission
problem. ASP.net unable to render image created in the memory and
hence error occur.
http://support.businessobjects.com/library/kbase/articles/c2013414.asp
http://support.businessobjects.com/library/kbase/articles/c2014843.asp
http://support.businessobjects.com/library/kbase/articles/c2014618.asp
Merge Modules
Once build is ready and wanted to deployed it on the development server. You
should add merge module in the build. This is important because you never know
that crystal report is installed on the development machine and it is not possible for
you to provide crystal report to the client. You can include following modules in the
build and it will take care of all the further issues of deployment on the server.
Crystal_managed2003.msm
Crystal_database_Access2003.msm
Crystal_datavase_Access2003.msm
Crystal_regwiz2003.msm
This creates a new schema file (Dataset1.xsd) that will be used to generate a
strongly-typed dataset. The schema file will be displayed in the ADO.NET Dataset
Designer.
Your database, its tables, and its fields now appear in the Server Explorer under the
Data Connections node.
To build a schema for your dataset, drag the desired tables from the Server Explorer
to the Dataset tab of Dataset1.xsd. Click Save Dataset1.xsd to save the
Dataset1.xsd file. On the Build menu, click Build to generate the dataset object for
the project.
There is another reason why I have created xsd (schema file) for report. Let us
consider a situation where you want to deploy your application on client's server.
Now situation is you have set location of crystal report to your development server
and though you set logon information programmatically logon failure occurs. To
overcome this problem, I have a view associated in schema file. I can set location of
ADO.NET Dataset to the xsd view and this will take care of all the problems for
setting location while runtime, since it is independent of any of the server and to
access dataset we are applying separate connection string from the web.config file.
This way you can get rid of all the problems to access crystal reports in asp.net.
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports CrystalDecisions.Shared
Imports CrystalDecisions.CrystalReports.Engine
Imports System.Configuration
Namespace CrystalReports
''' <summary>
''' Summary description for WebForm1.
''' </summary>
Public Class WebForm1
Inherits System.Web.UI.Page
Protected CrystalReportViewer1 As CrystalDecisions.Web.CrystalReportViewer
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
' Put user code to initialize the page here
End Sub 'Page_Load
Protected Overrides Sub OnInit(ByVal e As EventArgs)
'
' CODEGEN: This call is required by the ASP.NET Web Form Designer.
'
InitializeComponent()
MyBase.OnInit(e)
'Database connectivity
Dim mycon As New
SqlConnection(ConfigurationSettings.AppSettings("connectionString"))
Dim dtbl As New DataTable
Dim dtst As New DataSet
Dim sqdt As SqlDataAdapter
Try
'Database activity
sqdt = New SqlDataAdapter("SELECT * FROM ProductsList", mycon)
sqdt.Fill(dtbl)
dtst.Tables.Add()
Dim crptProList As New productList
crptProList.SetDataSource(dtst)
CrystalReportViewer1.DisplayGroupTree = False
CrystalReportViewer1.ReportSource = crptProList
'Passing parameter to the crystal report
'let us assume that i have added a parameter to the crystal report which
accepts
'categoryname and based on this generate report this parameter you can pass
'from any web form as a request parameter
'string catName = Request.QueryString["catageoryName"];
'you can set parameter after setting report source as below
PrivateSubInitializeComponent()
EndSub'InitializeComponent
EndClass'WebForm1
EndNamespace'CrystalReports
(Page 1 of 6 )
This is the second article in a series that covers programming with Crystal Reports with
ASP.NET 2.0. In this article, we will focus on working with parameters using Crystal
Reports and passing the parameter values from an ASP.NET 2.0 web site.
If you are new to Crystal report programming, I strongly suggest that you read the first
article in this series, Programming Crystal Reports with ASP.NET 2.0. This article uses
and enhances the solution (source code) provided at the above link.
The entire solution (source code) for this article is available as a free download in the
form of a zip. The source code in this article has been developed using Microsoft Visual
Studio 2005 Professional Edition on Microsoft Windows XP Professional Edition with
Microsoft SQL Server 2005 Express Edition. I used the same version of Crystal Reports
which comes with Visual Studio 2005 Professional Edition. I didn't test the code in any
other tools/IDEs/servers/editions/versions. If you have any problems, please feel free to
post in the discussion area.
Adding a single parameter to the Crystal Report at design time
Before proceeding further, open the "SampleWebSite01" website (available as a
download with this article) and add a new Crystal Report (named "SampleParam1.rpt")
focusing on the Orders table of the Northwind database. Make sure you add OrderID,
CustomerID, EmployeeID and OrderDate to the report. All of this is explained in the first
article of this series.
The following are the steps required to add a parameter to the Crystal report:
Using the "FieldExplorer," right click on "Parameter Fields" and click "New" as shown in
the following figure (01).
In the "Select Expert" dialog box, select the operator as "is equal to," select "{?
p_EmployeeID}" as the value (shown in Figure 05) and click OK.
Working with Parameters with Crystal Reports and ASP.NET 2.0 - Passing the value to
Crystal Report Parameter dynamically: source code
(Page 2 of 6 )
In the previous section, we added a parameter named "p_EmployeeID" to the report. Now it is time
to access the report (say, get a list of orders) based on the user specified value of Employee ID.
Let us modify the web page so that it looks like the following (Fig 06):
The Source for the above page design is as follows:
The explanation for the above code is provided in the next section.
Working with Parameters with Crystal Reports and ASP.NET 2.0 - Passing the value to
Crystal Report Parameter dynamically at run-time: explanation
(Page 3 of 6 )
First of all, you must observe that the CrystalDecisions.Shared namespace is added to work with
Crystal Reports-related classes and objects. In the previous section's code, the database connection
information is stored in ConnInfo and is defined as follows:
The above connection information is assigned to the CrystalReportViewer control using the following
code:
Me.CrystalReportViewer1.ParameterFieldInfo.Clear()
Me.CrystalReportViewer1.ReportSource = Server.MapPath("SampleParam1.rpt")
Dim ParamFields As ParameterFields =
Me.CrystalReportViewer1.ParameterFieldInfo
Dim p_EmpID As New ParameterField
p_EmpID.Name = "p_EmployeeID"
Dim p_EmpID_Value As New ParameterDiscreteValue
p_EmpID_Value.Value = Me.txtEmployeeID.Text
p_EmpID.CurrentValues.Add(p_EmpID_Value)
ParamFields.Add(p_EmpID)
End Sub
Add a new report named "SampleParam2.rpt" with the same fields, in a way that is similar to the
previous report. Now, we shall add a range value parameter to the Crystal Report.
The following are the steps to take to add a range value parameter:
In the "Create Parameter Field" dialog box, provide "Name" as "p_OrderDateRange," "Prompting
Text" as "Enter Start and End Dates," "Value Type" as "DateTime," select "Range Values" in the
"Options" and click OK (Fig 07).
In the "Choose Field" dialog box, select "Orders.OrderDate" and click on OK (as shown in figure 08).
Using the "Select Expert" provide information as follows (Fig 09) and click OK.
Working with Parameters with Crystal Reports and ASP.NET 2.0 - Passing the value to the
Crystal Report Range Parameter dynamically: source code
(Page 4 of 6 )
In the previous section, we added a parameter named "p_OrderDateRange" to the report. Now, it is
time to access the report (say, get a list of orders) based on the user-specified range of dates.
Let us modify the web page so that it looks like the following (Fig 10):
Working with Parameters with Crystal Reports and ASP.NET 2.0 - Adding Multiple Value
(Discrete and Range) parameters to Crystal Report
(Page 5 of 6 )
This is very similar to the previous report except that this accepts multiple values (both discrete and
range parameters).
In a way similar to the previous reports, add a new report named "SampleParam3.rpt" with the
same fields. Now we shall add a new parameter to the Crystal Report.
The following are the steps required to add multiple value (Discrete and Range) parameters:
Using the "Select Expert," provide the information for the "Choose Field" dialog box as being from
"Orders.OrderDate" and click on OK (as shown in figure 12).
Using the "Select Expert" provide information as follows (Fig 13) and click OK.
Working with Parameters with Crystal Reports and ASP.NET 2.0 - Passing the value to
Multiple Crystal Report Parameters dynamically: source code
(Page 6 of 6 )
Let us modify the web page so that it looks like the following (Fig 14):
I hope you enjoyed the article and any suggestions, bugs, errors, enhancements etc. are highly
appreciated at http://jagchat.spaces.live.com