Вы находитесь на странице: 1из 70

C# Crystal Reports Tutorial

1.C# Crystal Reports sample databse

For generating Crystal Reports from C# , we need to connect a database and


some tables with data. In the following section you can see how to create a
sample Database and Tables and the data for running of the following Crystal
Reports - C# Tutorial . All examples in the CSharp Crystal Reports Tutorial is
based on the following database .

First we have to create a database named it as "crystaldb"

Create DataBase "crystaldb"

In the crystaldb database , create three tables

OrderMaster , OrderDetails , Product .

The Table Structure follows :


OrderMaster
OrderMaster_id
OrderMaster_date
OrderMaster_customer

OrderMaster_createduser

OrderDetails
OrderDetails_id
OrderDetails_masterid
OrderDetails_productid

OrderDetails_qty

Product
Product_id
Product_name

Product_price

The following picture shows the relation of tables in crystaldb database :


SQL command for creating tables are follows :
CREATE TABLE [dbo].[OrderMaster] (
[OrderMaster_id] [int] NOT NULL ,
[OrderMaster_date] [datetime] NULL ,
[OrderMaster_customername] [varchar] (50),
[OrderMaster_createduser] [varchar] (50)

) ON [PRIMARY]

CREATE TABLE [dbo].[OrderDetails] (


[OrderDetails_id] [int] NOT NULL ,
[OrderDetails_masterid] [int] NULL ,
[OrderDetails_productid] [int] NULL ,
[OrderDetails_qty] [int] NULL

) ON [PRIMARY]

CREATE TABLE [dbo].[Product] (


[Product_id] [int] NOT NULL ,
[Product_name] [varchar] (50) ,
[Product_price] [numeric](18, 0) NULL

) ON [PRIMARY]

Enter some data to the tables :

From the following pictures you can see some data in the table for C# - Crystal
Reports tutorial
Order Master Table Data

Order Details Table Data

Product Table Data

2. C# Crystal Reports step by step

A step by step tutorial for beginners who is creating their Crystal Reports for
the first time in C#.

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb
Here we are going to create a new Crystal Reports in C# from Product table in
the above mentioned database crystalDB. The Product Table has three fields
(Product_id,Product_name,Product_price) and we are showing the whole data
from Product table to the C# - Crystal Reports project.

Open Visual Studio .NET and select a new CSharp Windows project.

Now you will get the default Form1.cs.

From the main menu in Visual Studio C# project select PROJECT-->Add New
Item . Then Add New Item dialogue will appear and select Crystal Reports
from the dialogue box.
Select Report type from Crystal Reports gallery.

Accept the default settings and click OK.

Next step is to select the appropriate connection to your database (here


crstaldb). Here we are going to select OLEDB Connection for SQL Server to
connect Crystal Reports in C#.

Select OLE DB (ADO) from Create New Connection .


Select Microsoft OLE DB Provider for SQL Server .

The next screen is the SQL Server authentication screen for connecting to the
database - crystalDB. Select your Sql Server name , enter userid , password and
select your Database Name .

Click next , Then the screen shows OLE DB Property values , leave it as it is ,
and then click finish button.
After you click the finish button , the next window you will get your Server
name under OLEDB Connection, from there selected database name
(Crystaldb) and click the tables , then you can see all your tables from your
database.

From the tables list double click the Product table then you can see the Product
table will come in the right side list.
Click Next Button

Select all fields from Product table to the right side list .

Click Finish Button. Then you can see the Crystal Reports designer window in
your C# project. In the Crystal Reports designer window you can see the
selected fields from Product table. You can arrange the field Objects and design
of the screen according your requirements. After that your screen is look like
the following picture.
Now the designing part is over and the next step is to call the Crystal Reports in
your C# application and view it through Crystal Reports Viewer control in C#.

Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .

After you drag the CrystalReportViewer to your form , it will look like the
following picture.

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

Copy and paste the following source code and run your C# project
using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH
HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

NOTES:

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your C# project file location, there you can see
CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt

When you run the source code you will get the report like the following picture.
When you click the button, the application will ask the username and password.
Later in this tutorial you can find how to avoid asking username and password -

3.C# Crystal Reports Dynamic Logon parameters

The following section describes how to pass the logon information like Server
Name , database Name , User Name and password dynamically to the Crystal
Reports from C# applications.

When you run the previous programs in this C# tutorial , the Crystal Reports
asks the Username and Password every time you run the Crystal Report. This
section explains how to avoid the dialogue box asking username and password
at runtime on Crystal Reports login . In this section we are passing User ID ,
Password , Server Name and Database Name dynamically to Crystal Reports
from C# .

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

In many situations dynamically passing the logon parameter fields are very
useful , for example if you develop a database project in a test server
environment and later you have to migrate it to other server , in these situations
it is better to give these information dynamically to Crystal Reports .

In step by step tutorial for creating a Crystal Reports from C# - we created a


report selecting all data from the Product table . There is no chance to change
the server name or any other information on runtime in that case, because it is a
static report and it will asks username and password every time you run the
Crystal Reports . Here we are passing Server Name , UserID and Password
dynamically to the Crystal Reports from our C# program

Here we use Crystal Reports ConnectionInfo class for passing connection


information.

ConnectionInfo crConnectionInfo = new ConnectionInfo();


Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Tables CrTables ;

cryRpt.Load("PUT CRYSTAL REPORT PATH


HERE\CrystalReport1.rpt");

crConnectionInfo.ServerName = "YOUR SERVER NAME";


crConnectionInfo.DatabaseName = "YOUR DATABASE NAME";
crConnectionInfo.UserID = "YOUR DATABASE USERNAME";
crConnectionInfo.Password = "YOUR DATABASE PASSWORD";

CrTables = cryRpt.Database.Tables ;
foreach (CrystalDecisions.CrystalReports.Engine.Table
CrTable in CrTables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}

crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your C# project files location, there you can
see CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt

You have to replace the source code values of


crConnectionInfo.ServerName = "YOUR SERVER NAME";

crConnectionInfo.DatabaseName = "YOUR DATABASE NAME";

crConnectionInfo.UserID = "YOUR DATABASE USERNAME";

crConnectionInfo.Password = "YOUR DATABASE PASSWORD";

with your real-time values .

4.C# Crystal Reports from multiple tables

The following section describes how to create Crystal Report from multiple
tables in C#.
All C# Crystal Reports Tutorial in this website is based on the following
database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

Here we are going to generate Crystal Reports from multiple tables in C#. Here
we have three tables (ordermaster , orderdetails and product ) and we are
generating a Crystal Report from these three tables by connecting each table
with their related fields.

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

Hope you understand the basics of generating a Crystal Reports in C# , this


section is the continuation of the first part, so here we avoid some basic steps
and start from the table selection of Crystal Reports.

Select all table from the table list to right side list box, because we are creating
report from three tables ( OrderMaster, OrderDetails, Product) . If you don't
know up to this part of the tutorial , refer previous tutorial for up to selecting
databese for Crystal reports.

The next step is to make relations between these selected tables. Here we are
connecting the related fields from each table. For that we arrange the tables in
visible area in the list (this is not necessary ) and select the fields that we want
to make relation and drag to the related field of the other selected tables. After
made the relations with tables the screen is look like the following picture .
Next step is to select the fields from the selected tables ( OrderMaster,
OrderDetails, Product) . Here we are selecting the fields Customername ,
orderdate from ordermastertable , Productname from product table and quantity
from order details table. The field selection screen is look like the following
picture .

After select the fields from tables, click the Finish button because now we are
not using any other functionalities of the Crystal Reports wizard. After that you
will get the Crystal Reports designer window . You can arrange the fields in the
designer window according to your requirement to view the report .

For re-arranging fields in the designer window , you can drag the field object
on the screen . For editing right click the field object and select Edit Text
Object. The following picture shows the sample of designer window after
rearrange the field.

Now the designing part is over and the next step is to call the Crystal Reports in
C# and view it in Crystal Reports Viewer control .

Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .
After you drag the CrystalReportViewer to your form , it will look like the
following picture.

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH
HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}
NOTES:

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your C# project files location, there you can
see CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt

After you run the source code you will get the report like this.

When you click the button, the application will ask the username and password.
Later in this tutorial you can find how to avoid asking username and password

5. C# Crystal Reports String parameter

The following section describes how to pass a String parameter to Crystal


Reports from C# application.

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.
Here we pass a String parameter from C# to Crystal Reports . For example ,
from C# program we pass a customer name as a parameter and show all the
orders of that customer to the Crystal Reports.

In the previous tutorial we saw how to generate a C# - Crystal Reports from


multiple tables. This program is the continuation of previous tutorial , the only
difference is that we pass a Customer Name as String parameter and get the
report of that particular Customer only . Before starting to this section just take
a look at the previous section C# Crystal Reports from multiple tables.

In the previous section we are getting the report of all orders from all customers
, that is , all orders placed by all customers . In this section we pull out the
selected customer report only by passing Customer name as argument.

Hope you understand the previous section well, if not, please click here C#
Crystal Reports from multiple tables.

Next step is to create a String parameter in Crystal report designer window .

Select the Field Explorer from CrystalReport Menu. (Up to here explained in
detail in the previous section C# Crystal Reports from multiple tables)

Then you can see Field Explorer in the Left hand side.

Select Parameter Field from Field Explorer and right Click on Parameter Field.
Fill the appropriate name for Name and Prompting text fields like the following
picture.

After creating the parameter field , we have to create the selection formula for
the Crystal Reports parameter.

For creating selection formula , Right click on Crystal Reports designer


window , select REPORT -> SELECTION FORMULA -> RECORD .
Now you can see the record Selection Formula Editor Screen. For creating
selection formula , you have to select the fields from above field list and make
the formula .

First you have to select OrderMaster.OrderMaster_customername from Report


Field and select the comparison operator and select the parameter field. Double
click each field then it will be selected.

Form the following picture you can understand how to select fields.

You can close Selection Formula Editor screen after creating selection formula.

Now the designing part is over and the next step is to call the Crystal Reports in
C# and view it in Crystal Reports Viewer control .

Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C#
Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load("PUT CRYSTAL REPORT PATH
HERE\CrystalReport1.rpt");

ParameterFieldDefinitions crParameterFieldDefinitions ;
ParameterFieldDefinition crParameterFieldDefinition ;
ParameterValues crParameterValues = new ParameterValues();
ParameterDiscreteValue crParameterDiscreteValue = new
ParameterDiscreteValue();

crParameterDiscreteValue.Value = textBox1.Text;
crParameterFieldDefinitions =
cryRpt.DataDefinition.ParameterFields;
crParameterFieldDefinition =
crParameterFieldDefinitions["Customername"];
crParameterValues =
crParameterFieldDefinition.CurrentValues;

crParameterValues.Clear();
crParameterValues.Add(crParameterDiscreteValue);
crParameterFieldDefinition.ApplyCurrentValues(crParameterVal
ues);

crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();

}
}
}

NOTE :

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your C# project files location, there you can
see CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt

Now you can run the program . Enter a Customer Name(enter any existing
customer from Ordermaster table) and click the button , then your report is look
like the following picture.

C# Crystal Reports Integer parameter

The following section describes the how to pass an Integer Parameter to Crystal
Reports from C#

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.
In the previous tutorial , we already saw how to pass a String parameter to the
Crystal Reports from C# - C# Crystal Reports String Paramater - and get the
result. This section is almost same as the previous section and the only
difference is that instead of String parameter here we pass an Integer parameter
from C# . So before we start this section you can take look at the previous
section C# Crystal Reports String Paramater , it explain each steps in details
with pictures.

When we pass an Integer parameter , we have to create a new Integer parameter


in the Parameter Fields of Field Explorer. Then we will get the following
screen and fill the fields like in the following picture .

After creating the parameter field , we have to create the selection formula for
the Crystal Reports . For creating selection formula , Right click on Crystal
Reports designer window , select REPORT -> SELECTION FORMULA ->
RECORD .

Then you can see the record Selection Formula Editor. You can make selection
formula from this screen by choosing fields from the lists in the selection
formula editor screen.

Here only the Product table is selected for generating Crystal Reports . We are
making a formula like select the records from Product table whose value is
greater than the input value. For that, first we select the table field that is
Product_price from Product table and then we select the comparison operator
and finally we select our Parameter we created earlier. The following picture
shows how to select fields from lists . Double click each field then it will
automatically selected .
You can close the Selection Formula Editor screen after creating the formula.

Now the designing part is over and the next step is to call the Crystal Reports in
C# and view it in Crystal Reports Viewer control .

Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load("PUT CRYSTAL REPORT PATH
HERE\CrystalReport1.rpt");

ParameterFieldDefinitions crParameterFieldDefinitions ;
ParameterFieldDefinition crParameterFieldDefinition ;
ParameterValues crParameterValues = new ParameterValues();
ParameterDiscreteValue crParameterDiscreteValue = new
ParameterDiscreteValue();

crParameterDiscreteValue.Value =
Convert.ToInt32(textBox1.Text);
crParameterFieldDefinitions =
cryRpt.DataDefinition.ParameterFields;
crParameterFieldDefinition =
crParameterFieldDefinitions["Price"];
crParameterValues =
crParameterFieldDefinition.CurrentValues;

crParameterValues.Clear();
crParameterValues.Add(crParameterDiscreteValue);
crParameterFieldDefinition.ApplyCurrentValues(crParameterVal
ues);

crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();

}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your C# project files location, there you can
see CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt
Now you can run the program . Enter any price , then you can see the report of
the Product list whose price is greater than or equal to the entered price.
The Crystal Reports showing the result of Product list whose price is greater
than 50.

6. C# Crystal Reports Date parameter

The following section describes how to pass a Date parameter field from C# to
Crystal Reports.

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

In the previous sections , we already saw how to pass a string parameter to


Crystal Reports - C# Crystal Reports String Paramater, how to pass an Integer
parameter to Crystal Reports - C# Crystal Reports Integer Paramater and get
the result. This section is very similar to the previous two sections , so before
we begin this section , take a look at the previous two sections.

C# Crystal Reports Integer Paramater

When we pass a Date parameter from C# , we have to create a new date


parameter in the Parameter Fields of Field Explorer. Then we will get the
following screen and fill the fields like in the picture .
After creating the date parameter field , we have to create the selection formula
for the Crystal Reports . For creating selection formula , Right click on Crystal
Reports designer window , select REPORT -> SELECTION FORMULA ->
RECORD .

Then you can see the record Selection Formula Editor. You can make selection
formula from this screen by choosing fields from the lists in the selection
formula editor screen.

Here we have three tables selected for report (ordermaster , orderdetails and
product ) and we are making the formula like , select all records details from
the tables whose order date is greater than the input date parameter. For doing
this you have to select Ordermaster.orderdate , a comparison operator and
parameter date field from selection list of Formula Editor and make the
formula. The following picture shows how to select the fields from formula
editor and make the formula. Double click each field then it will automatically
selected .

You can close Selection Formula Editor screen after creating the formula.

Now the designing part is over and the next step is to call the Crystal Reports in
C# and view it in Crystal Reports Viewer control .

Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C#
Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

Copy and paste the following source code and run your C# project

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your C# project files location, there you can
see CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt

Now you can run the program . Enter any date , then you can see the report
whose order date is greater than or equal to the entered date.

Here we got the result of orders whose date is greater than the entered date.

7. C# Crystal Reports Dynamic Logon parameters

he following section describes how to pass the logon information like Server
Name , database Name , User Name and password dynamically to the Crystal
Reports from C# applications.

When you run the previous programs in this C# tutorial , the Crystal Reports
asks the Username and Password every time you run the Crystal Report. This
section explains how to avoid the dialogue box asking username and password
at runtime on Crystal Reports login . In this section we are passing User ID ,
Password , Server Name and Database Name dynamically to Crystal Reports
from C# .

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

In many situations dynamically passing the logon parameter fields are very
useful , for example if you develop a database project in a test server
environment and later you have to migrate it to other server , in these situations
it is better to give these information dynamically to Crystal Reports .

In step by step tutorial for creating a Crystal Reports from C# - we created a


report selecting all data from the Product table . There is no chance to change
the server name or any other information on runtime in that case, because it is a
static report and it will asks username and password every time you run the
Crystal Reports . Here we are passing Server Name , UserID and Password
dynamically to the Crystal Reports from our C# program

Here we use Crystal Reports ConnectionInfo class for passing connection


information.

ConnectionInfo crConnectionInfo = new ConnectionInfo();

Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

Copy and paste the following source code and run your C# project
using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Tables CrTables ;

cryRpt.Load("PUT CRYSTAL REPORT PATH


HERE\CrystalReport1.rpt");

crConnectionInfo.ServerName = "YOUR SERVER NAME";


crConnectionInfo.DatabaseName = "YOUR DATABASE NAME";
crConnectionInfo.UserID = "YOUR DATABASE USERNAME";
crConnectionInfo.Password = "YOUR DATABASE PASSWORD";

CrTables = cryRpt.Database.Tables ;
foreach (CrystalDecisions.CrystalReports.Engine.Table
CrTable in CrTables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}

crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your C# project files location, there you can
see CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt

You have to replace the source code values of


crConnectionInfo.ServerName = "YOUR SERVER NAME";

crConnectionInfo.DatabaseName = "YOUR DATABASE NAME";

crConnectionInfo.UserID = "YOUR DATABASE USERNAME";

crConnectionInfo.Password = "YOUR DATABASE PASSWORD";

with your real-time values .

8. C# Crystal Reports Formula Field

The following C# - Crystal Reports section describes how to add a formula


field in the Crystal Reports .

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

The situations when formula field is using :

If you have a Crystal Reports with Qty and Price fields and you need an
additional field in your Crystal Reports for Total, that is TOTAL = QTY X
PRICE . In these types of situations you can use the Formula Field in Crystal
Reports.

In this C# Crystal Reports tutorial we are showing that all orders with qty and
price and the total of each row , that means each in each row we are showing
the total of qty and price.

Before starting this tutorial Create a new Crystal Reports with fields
CustomerName , Order Date , Product Name and Product Price . If you do not
know how to create this report , just look the previous tutorial C# Crystal
Reports from multiple tables . In that report selecting only four fields , here we
need one more field Product->Price and one formula field Total.

After you create the above Crystal Reports, your CR designer screen is look
like the following picture :

Next step is to create a Formula Field for showing the result of Qty X Price .

Right Click the Formula Field in the Field Explorer and click New. Then you
will get an Input Message Box , type Total in textbox and click Use Editor.

Now you can see the Formula Editor screen . Here you can enter which formula
you want . Here we want the result of Qty X Price . For that we select
OrderDetails.Qty , the multipy operator (*) and Product.Price . Double click
each field for selection.

Now you can see Total Under the Formula Field . Drag the field in to the
Crystal Reports where you want to display Total.

Now the designing part is over and the next step is to call the Crystal Reports in
C# and view it in Crystal Reports Viewer control .

Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

Copy and paste the following source code and run your C# project
using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH
HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your C# project files location, there you can
see CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt

When you run this program you will get your screen like the following picture.
9. C# Crystal Reports Summary Field

The following C# - Crystal Reports section describes how to add a summary


field in the Crystal Reports .

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

This section is the continuation of the previous tutorial C# Crystal Reports


Formula Field . So before we start this tutorial , take a look at the previous
tutorial C# Crystal Reports Formula Field .

Hope you already gone through the previous section C# Crystal Reports
Formula Field. Here in this section we are calculating the grand total of the
Formula Field - Total . The Total field is a Formula field, the result of qty X
price .

In the Crystal Reports designer view window, right click on the Report Footer ,
just below the Total field and select Insert -> Summary .

Then you will get a screen , select the Total from the combo box and select
Sum from next Combo Box , and summary location Grand Total (Report
Footer) . Click Ok button
Now you can see @Total is just below the Total field in the report Footer.

Now the designing part is over and the next step is to call the Crystal Reports in
C# and view it in Crystal Reports Viewer control .

Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

Copy and paste the following source code and run your C# project
using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH
HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your C# project files location, there you can
see CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt

When you run this program your screen will look like the following picture.

10. C# Crystal Reports Export to Pdf

There are situations when we want to export Crystal reports to .pdf format
programmatically. In these situations we can use ExportOptions for export the
Crystal Reports to .pdf format. Also we have to set
PdfRtfWordFormatOptions and ExportFormatType.PortableDocFormat . In
the following example you can see how to export a Crystal Reports as a PDF
format file in C#.
All C# Crystal Reports Tutorial in this website is based on the following
database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

In this section we are using our earlier program step by step tutorial for creating
a Crystal Reports from C# for pull data from database to Crystal Reports .
Before we start this section take a look at the step by step tutorial for creating a
Crystal Reports from C# .

Here we are making a Crystal Report from Product table and export the report
content to a PDF format file.

Select the default form (Form1.cs) you created in C# and drag two buttons
(Button1, Button2 ) and a CrystalReportViewer control to your form.

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
ReportDocument cryRpt;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH
HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}

private void button2_Click(object sender, EventArgs e)


{
try
{
ExportOptions CrExportOptions ;
DiskFileDestinationOptions CrDiskFileDestinationOptions
= new DiskFileDestinationOptions();
PdfRtfWordFormatOptions CrFormatTypeOptions = new
PdfRtfWordFormatOptions();
CrDiskFileDestinationOptions.DiskFileName =
"c:\\csharp.net-informations.pdf";
CrExportOptions = cryRpt.ExportOptions;
{
CrExportOptions.ExportDestinationType =
ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType =
ExportFormatType.PortableDocFormat;
CrExportOptions.DestinationOptions =
CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
}
cryRpt.Export();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your C# project files location, there you can
see CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt

When you run this program you will get the PDF file (csharp.net-
informations.pdf) in your computer's C:\

11. C# Crystal Reports Export to Excel


There are situations when we want to export Crystal reports to .xls format
programmatically in C#. In these situations we can use ExportOptions for
export the Crystal Reports to .xls format. Also we have to set
ExcelFormatOptions and ExportFormatType.Excel . In the following example
you can see how to export a Crystal Reports as a Excel format file.

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

In this section we are using our earlier program step by step tutorial for creating
a Crystal Reports from C# for pull data from database to Crystal Reports .
Before we start this section take a look at the step by step tutorial for creating a
Crystal Reports from C# .

Here we are generating a Crystal Report from Product table and export the
report content to an Excel format file.

Select the default form (Form1.cs) you created in C# and drag two buttons
(Button1, Button2 ) and a CrystalReportViewer control to your form.

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
ReportDocument cryRpt;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH
HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}

private void button2_Click(object sender, EventArgs e)


{
try
{
ExportOptions CrExportOptions ;

DiskFileDestinationOptions CrDiskFileDestinationOptions
= new DiskFileDestinationOptions();
ExcelFormatOptions CrFormatTypeOptions = new
ExcelFormatOptions();
CrDiskFileDestinationOptions.DiskFileName =
"c:\\csharp.net-informations.xls";
CrExportOptions = cryRpt.ExportOptions;
CrExportOptions.ExportDestinationType =
ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType =
ExportFormatType.Excel;
CrExportOptions.DestinationOptions =
CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
cryRpt.Export();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");


The Crystal Reports file path in your project files location, there you can see
CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt

When you run this program you will get the Excel file (csharp.net-
informations.xls) in your computer's C:\

12. Email Crystal Reports from C# Application

The following program describes how to email a Crystal Reports from C# .

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

For email a Crystal Report from C# first we have to export the Crystal Reports
in any of the File Format available in Crystal Reports and then Email it.

In this section we use the previous tutorial C# Crystal Reports Export to PDF
file . So before we start this section please take a look at the tutorial C# Crystal
Reports Export to PDF file.

After export the Crystal Reports as a PDF file format in your disk , the next
step is to email that .pdf file . For that here we are using System.Web.Mail of
C# . We have to provide the necessary information to configuring SmtpMail
client and send the exported file as attachment .

Select the default form (Form1.cs) you created in C# and drag two buttons
(Button1, Button2 ) and a CrystalReportViewer control to your form.

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;
using System.Web.Mail

Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Web.Mail;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
ReportDocument cryRpt;
string pdfFile = "c:\\csharp.net-informations.pdf";

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH
HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}

private void button2_Click(object sender, EventArgs e)


{
try
{
ExportOptions CrExportOptions ;
DiskFileDestinationOptions CrDiskFileDestinationOptions
= new DiskFileDestinationOptions();
PdfRtfWordFormatOptions CrFormatTypeOptions = new
PdfRtfWordFormatOptions();
CrDiskFileDestinationOptions.DiskFileName = pdfFile;
CrExportOptions = cryRpt.ExportOptions;
CrExportOptions.ExportDestinationType =
ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType =
ExportFormatType.PortableDocFormat;
CrExportOptions.DestinationOptions =
CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
cryRpt.Export();

sendmail();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

private void sendmail()


{
try {
SmtpMail.SmtpServer.Insert(0, "your hostname");
MailMessage Msg = new MailMessage();
Msg.To = "to address here";
Msg.From = "from address here";
Msg.Subject = "Crystal Report Attachment ";
Msg.Body = "Crystal Report Attachment ";
Msg.Attachments.Add(new MailAttachment(pdfFile));
System.Web.Mail.SmtpMail.Send(Msg);
}
catch (Exception ex) {
MessageBox.Show (ex.ToString());
}
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your C# project files location, there you can
see CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt

Before you run this program , you have to provide the necessary SMTP
information , that is your HOSTNAME , FROM ADDRESS and TO
ADDRESS to the SMTP client.

13. C# Crystal Reports without database

Usually we are using Crystal Reports to fetch data from databases and show it
as a report. Here we are generating a Crystal Reports from C# without using a
database . For generating a Crystal Reports without database , here we are
using a Strongly Typed Dataset and a Data Table of C#.

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.
Generating a Strongly Typed DataSet

Create a new C# Project and create a Dataset from Project - Add New Item
Dialogue Box.

Select Dataset from list

Accept the default name DataSet1.xsd .

Create a data table for DataSet1.xsd in C#.


Select DataSet1.xsd from Solution Explorer and right click . Select datatable
from the menu. Then you will get a datatable in the Datast . Right click the
datatable and select Add-Column .

Here we are making a two column Crystal Reports , so we need two column in
the data table . Add and ID column and Item column in the Data Table.

Now the dataset part is over . Next step is to create a Crystal Reports from the
Dataset we created. Select a new Crystal Reports from Add New Item menu
and accept the default settings. The next screen is to select appropriate data
source . There you can find the Datatable1 from Project data - ADO.NET
Datasets , and select Datatable1 to the right side.
Click Next button and select ID and Item from the datatable1 to right side and
click finish.

Now the C# Crystal Reports designer part is over . Next part is to create data
for the Crystal Reports . For that we have to create a Data Table through
programmatically and add data to dataset1.

Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .

Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Data;

namespace WindowsApplication1
{
public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
DataSet1 ds = new DataSet1();
DataTable t = ds.Tables.Add("Items");
t.Columns.Add("id", Type.GetType("System.Int32"));
t.Columns.Add("Item", Type.GetType("System.String"));
DataRow r ;
int i = 0;
for (i = 0; i <= 9; i++)
{
r = t.NewRow();
r["id"] = i;
r["Item"] = "Item" + i;
t.Rows.Add(r);
}

CrystalReport1 objRpt = new CrystalReport1();


objRpt.SetDataSource(ds.Tables[1]);
crystalReportViewer1.ReportSource = objRpt;
crystalReportViewer1.Refresh();
}
}
}

14. C# Crystal Reports from SQL Query

The following section describes how to create a Crystal Reports in C# using


SQL Query String .

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at
the database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

Generating a Strongly Typed DataSet

Here we are using a Strongly Typed Dataset for generating a Crystal Reports
from SQL Query string . Before start this section , you can take look at the
previous section of how to create a C# Crystal Report from Strongly Typed
Dataset. Because here we are using Strongly Typed Dataset for generating
Crystal Report from SQL Query string.

Here we are generating a report against the Product table . So we are passing
the following sql and generating the report

sql = "SELECT Product_id,Product_name,Product_price FROM Product";

Create a new C# project and create a new Strongly Typed Dataset from
Project - Add New Item Dialogue Box.

Add three column in the Strongly Typed Dataset .


Product_id
Product_name

Product_price

Create a new Crystal Report and select DataTable as Data Source . You can
select DataTable from the wizard , Project Data - ADO.NET Dataset -
Crystal report Dataset1 - dataset1. Click the Next Button.

Select fields ( Product_id , Product_name , Product_price ) from the next


screen and click the finish button. Then you will get the designer screen with
the selected fields. If you do not know how to create a dataset , refer the
previous section How to create a C# Crystal Report from Strongly Typed
Dataset.

Now the designing part is over. From the source code we can pass the SQL
source code to Crystal Reports.

Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Data;
using System.Data.SqlClient ;

namespace WindowsApplication1
{
public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
SqlConnection cnn ;
string connectionString = null;
string sql = null;

connectionString = "data source=SERVERNAME;initial


catalog=DATABASENAME;user id=USERNAME;password=PASSWORD;";
cnn = new SqlConnection(connectionString);
cnn.Open();
sql = "SELECT Product_id,Product_name,Product_price FROM
Product";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet1 ds = new DataSet1();
dscmd.Fill(ds, "Product");
MessageBox.Show (ds.Tables[1].Rows.Count.ToString());
cnn.Close();

CrystalReport1 objRpt = new CrystalReport1();


objRpt.SetDataSource(ds.Tables[1]);
crystalReportViewer1.ReportSource = objRpt;
crystalReportViewer1.Refresh();
}
}
}

connectionString = "data source=SERVERNAME;initial


catalog=DATABASENAME;user
id=USERNAME;password=PASSWORD;";

You have to provide the necessary database information to


Connection String.

15. C# Crystal Reports from XML

Usually we are generating Crystal Reports from Databases , here in the


following section describes how to create a Crystal reports from XML file in
C#. This is very similar to creating Crystal Reports from database , the only
difference is that you have to select the data source as the XML file at the
designing time of Crystal Report in C#.

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

In order to generating Crystal Report from XML file , we have to create an


XML file . Here we are going to create an XML file and name it as
Product.XML . The structure of the Product.XML file is same as the Product
table in the crystaldb database earlier mentioned in this section C# crystaldb .
The content of the product.xml is shown below.

Download Product.XML

Generating Crystal Report from XML file is very similar to generating Crystal
Report from Databases. The only difference is happened when you selecting
the datasource part. Here you have to select Create New Connection -
Database Files and select the XML file you want to generate Crystal Reports
(In this case you select the Product.xml ).
Select all the fields from Product and click finish button

Now the designing part is over and the next step is to call the Crystal Reports in
C# and view it in Crystal Reports Viewer control .

Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH
HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

NOTES:

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your C# project files location, there you can
see CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt

16. C# Crystal Reports - sub reports

The following progrm describes how to create a sub report within a Crystal
Report in C#.

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

Subreport in Crystal Reports means that a report inside a Crystal Report . When
we want to show some additional information about a data field in a Crystal
Reports row, we use the subreports features to show the details. We can display
sub report in two ways , one is to show subreport directly under the main row
details. The other method is to show it as C# Crystal Reports on demand sub-
reports , that means we put an Hyper link just below the row filed , and when
the user click that hyper link it will show the subreport.
In this section we are going to generate a sub-report under the main row details.
That is for each row there is a subreoprt for the details.

Here we are going create an order report based on three tables in the database
and show a subreoprt for each row field of Product Name. Here we are using
our earlier program C# Crystal Reports from multiple tables to show the main
Crystal Reports Data , so refer C# Crystal Reports from multiple tables , before
start this section .

Create a Crystal Reports using three tables and select customername , date ,
product and qty . It will explain in detail the previous section C# Crystal
Reports from multiple tables.

Next step is to create a sub report inside the main report. Here we are showing
the Product details in each row of the specified product in the main row.

After create the main report , right click on Crystal Reports designer window
and select Insert-Subreport.
Then you will get the subreport object , drag the object in the designer window
at the down part of the details tab , just below the fields in the details tab. When
you release the mouse you will get a dialogue box asking report name . Enter a
report name , and click the Report Wizard Button .

The wizard shows the table selection screen and select the table . Here in this
case we have to select the Product Table from the list and click next .

Next screen is showing the table , from there select the fields you want to show
the data and click finish. The you will get the sub report main screen again and
select Link tab .

The link tab is making relation with your main Report and subreport . Here we
are linking the productname from main report to the subreport. For that select
Product.Product_name from Available fields.

Accept the other settings as it is in the screen and click ok. Now you can see the
sub report object in the screen , if you want to re-arrange subreport design ,
double click on subreport object then you can design subreport.
Now the designing part is over and the next step is to call the Crystal Reports in
C# and view it in Crystal Reports Viewer control .

Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH
HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

17. C# Crystal Reports - on demand sub reports

The following program shows how to create a Crystal Report On Demand


Subreport in C#.
All C# Crystal Reports Tutorial in this website is based on the following
database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

In the previous section of C# Crystal Reports sub-reports is described how to


insert a subreport in Crystal Reports . In the previous section the sub report is
displayed directly under each row details of main report .

The following section explains how to display subreport when the user click in
a hyper link in the main Crystal Report . In this case the sub report has only a
link to the main Report . That is when the user click the link , then only the
subreport display , it is called On Demand Report .

This section is the continuation of the previous section C# Crystal Reports sub-
reports. Here we are creating a Sub report in Crystal Report and make a link in
the main Crystal Reports for on-demand subreport.

Select the subreport object in the Crystal Reports and right click , then select
Format Object .
Then you will get the Format Editor . Select Sub report tab from Format
Editor , you can find there a check box - On-demand Subreport . You have to
select that check box , then the sub report become as a link in your main
Crystal Reports. If you want to change the title , you can change it in subreport
name textbox. Finally click OK button.

Now the designing part is over and the next step is to call the Crystal Reports in
CSharp and view it in Crystal Reports Viewer control .

Now the designing part is over and the next step is to call the Crystal Reports in
C# and view it in Crystal Reports Viewer control .

You have to include CrystalDecisions.CrystalReports.Engine in your C#


Source Code.

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

Copy and paste the following source code and run your C# project
using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH
HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

18. C# Crystal Reports - Date to Date

The following program describes how to generate a Date to Date report from
Crystal Reports in C#

All C# Crystal Reports Tutorial in this website is based on the following


database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

In the previous sections explains How to pass C# Crystal Reports Date


Paramater and also explain C# Dynamic logon parameters in Crystal Reports.
So before we start this section take a look at the previous sections because we
are here using sections from these tutorial.

Hope you understand the previous two sections well (1 - C# Crystal Reports
Date Paramater, 2 - C# Dynamic logon parameters in Crystal Reports). Here we
are creating two date parameter and pass it to Crystal Report at run time also
the Crystal Report using dynamic logon parameter to access database.
Createting two date parameters (dateFrom and dateTo).

Date From parameter.

Date To Parameter

Here we have three tables selected for report (ordermaster , orderdetails and
product ) and we are making the formula like , select all records from the tables
whose order date is between fromDate parameter and toDate paramater . For
doing this you have to select from date as Ordermaster.orderdate, to date as
Ordermaster.orderdate , comparison operators , boolean operator (AND) and
date parameters fromdate and todate fields from selection list of Formula Editor
and make the formula.

The following picture shows how to select the fields from formula editor and
make the formula. Double click each field then it will automatically selected .
After the creation of selection formula you can close that screen .

Now the designing part is over and the next step is to call the Crystal Reports in
C# and view it in Crystal Reports Viewer control .

Select the default form (Form1.cs) you created in CSharp and drag two
Textboxs (from date entry and to date entry) , a button and
CrystalReportViewer control to your form.

Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load("PUT CRYSTAL REPORT PATH
HERE\CrystalReport1.rpt");
TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Tables CrTables;

ParameterFieldDefinitions crParameterFieldDefinitions ;
ParameterFieldDefinition crParameterFieldDefinition ;
ParameterValues crParameterValues = new ParameterValues();
ParameterDiscreteValue crParameterDiscreteValue = new
ParameterDiscreteValue();

crParameterDiscreteValue.Value = textBox1.Text;
crParameterFieldDefinitions =
cryRpt.DataDefinition.ParameterFields;
crParameterFieldDefinition =
crParameterFieldDefinitions["fromDate"];
crParameterValues =
crParameterFieldDefinition.CurrentValues;

crParameterValues.Clear();
crParameterValues.Add(crParameterDiscreteValue);
crParameterFieldDefinition.ApplyCurrentValues(crParameterVal
ues);

crParameterDiscreteValue.Value = textBox2.Text;
crParameterFieldDefinitions =
cryRpt.DataDefinition.ParameterFields;
crParameterFieldDefinition =
crParameterFieldDefinitions["toDate"];
crParameterValues =
crParameterFieldDefinition.CurrentValues;

crParameterValues.Add(crParameterDiscreteValue);
crParameterFieldDefinition.ApplyCurrentValues(crParameterVal
ues);

crConnectionInfo.ServerName = "YOUR SERVERNAME";


crConnectionInfo.DatabaseName = "DATABASE NAME";
crConnectionInfo.UserID = "USERID";
crConnectionInfo.Password = "PASSWORD";

CrTables = cryRpt.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table
CrTable in CrTables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}

crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your project files location, there you can see
CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt
crConnectionInfo.ServerName = "YOUR SERVERNAME";

crConnectionInfo.DatabaseName = "DATABASE NAME";

crConnectionInfo.UserID = "USERID";

crConnectionInfo.Password = "PASSWORD";

You have to pass the necessary database connection information.

Now you can run the program . Enter from date and to date , then you can see
the report whose order date is between from date and to date you passed to
Crystal reports.

19. How to print Crystal Reports in C#

The following program shows how to print multiple copies of Crystal reports
from C#.
All C# Crystal Reports Tutorial in this website is based on the following
database - crystaldb. So before you begin this section , please take a look at the
database structure of crystaldb - Click Here C# crystaldb

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

The following program generate a Crystal Reports from product table and print
2 copies of report without using CrystalReportViewer in C#. The program
generate report from Product table , the step by step tutorial for creating a
Crystal Reports from C# section explains how to create report from Product
table. Also the program dynamically passing the logon parameters to Crystal
Report. If you don't know how to pass dynamic logon parameter please take a
look at the section C# Dynamic logon parameters in Crystal Reports.

Hope you understand the previous section well. Create a Crystal report from
Product Table and copy and paste the following source code in the project.

Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load("PUT CRYSTAL REPORT PATH
HERE\CrystalReport1.rpt");

TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();


TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Tables CrTables;

crConnectionInfo.ServerName = "YOUR SERVERNAME";


crConnectionInfo.DatabaseName = "DATABASE NAME";
crConnectionInfo.UserID = "USERID";
crConnectionInfo.Password = "PASSWORD";

CrTables = cryRpt.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table
CrTable in CrTables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}

cryRpt.Refresh();
cryRpt.PrintToPrinter(2, true, 1, 2);

}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your project files location, there you can see
CrystalReport1.rpt . So give the full path name of Crystal Reports file like
c:\projects\crystalreports\CrystalReport1.rpt
crConnectionInfo.ServerName = "YOUR SERVERNAME";

crConnectionInfo.DatabaseName = "DATABASE NAME";

crConnectionInfo.UserID = "USERID";

crConnectionInfo.Password = "PASSWORD";

You have to pass the necessary database connection information.

Now you can run the program . When you run this program the program will
print multiple copies of Crystal Reports.

20. How to deploy Crystal Report

The following section describes how to deploy a Crystal Reports components


and assemblies on the target machine.
If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

Crystal Reports for Visual Studio ships with your deployment projects that
enable you to deploy Crystal Reports components and assemblies on the target
machine. We can use different approaches to install Crystal Reports runtime
files on the target machine in order to run your C# applications smoothly.

If you are using Visual Studio then during your setup and deployment you can
add the CRRedist2005_x86.msi file to your setup file and distribute it as a
single setup file with your C# application. The installer can execute the setup
file automatically within your .Net Project in a single click. You can find the
CRRedist2005_x86.msi file in your system's C:\Program Files\Microsoft
Visual Studio 8\SDK\v2.0\BootStrapper\Packages\CrystalReports . Also you
can distribute the CRRedist2005_x86.msi separately and install it on the target
machine where your C# applications installed.

The other way to install Crystal Reports on target machine is to create a setup
file using Merge Modules and distribute it with your C# application or as a
separate setup file. Click the following link to see how to make a setup file with
Merge Modules.

21. How to Crystal Report Merge Module

The following section shows how to create a setup file for Crystal Reports
Client side installations using Merge Modules.

If you are new to Crystal Reports and do not know how to create Crystal
Reports from C# , please take a look at the section step by step tutorial for
creating a Crystal Reports from C#.

In the previous section How to install C# Crystal Reports on Clinet machine ,


we already saw how to deploy a Crystal Reports components and assemblies on
the target machine using CRRedist2005_x86.msi file. Here we are creating a
separate setup file for client side installations using Crystal Report Merge
Modules.

Crystal Reports uses merge modules to ensure the correct report components
and assemblies are installed with your deployment of C# project. A merge
module is a set of components that are merged with a Windows installer for
applications that need them. The following steps are creating a setup file for
Crystal Reports Client side installation using Merge Modules.

Before creating a setup project, make sure that the following files exist in the
\Program Files\Common Files\Merge Modules folder.
CrystalReportsRedist2005_x86.msm
Microsoft_VC80_ATL_x86.msm

policy_8_0_Microsoft_VC80_ATL_x86.msm

Steps to create Setup file for your C# Application.

1) Make sure the above mentioned files are in the \Program Files\Common
Files\Merge Modules folder , If the files are not there you can download the file
and copy it to the folder \Program Files\Common Files\Merge Modules .

Download: https://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/11688

2) Open your Visual Studio

3) Select "New Project" from File menu.

4) Select "Setup and Deployment" from "Other Project Types"

5) In the "Solution Explorer", select your setup project, right-click, and select
Add and Merge Module from the menu.
6) Select CrystalReportsRedist2005_x86.msm to your setup project.

The file available at \Program Files\Common Files\Merge Modules

Then you can see Microsoft_VC80_ATL_x86.msm and


policy_8_0_Microsoft_VC80_ATL_x86.msm will be automatically added in
the Detected Decencies section.

7) Build your project.

Now you will get the setup file for distribution. Either you can add this setup
file to your C# application installer or distribute it as a separate setup file.