Thursday, 1 December 2011

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.
csharp-crystal-reports-datefrom
Date To Parameter
csharp-crystal-reports-dateto
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 .
csharp-crystal-reports-datetodate-formula
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.



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(crParameterValues);

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

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

            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.

csharp-crystal-reports-date-to-date

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.
crystal-reports-deploymet-1
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.
crystal-reports-merge-module
6) Select CrystalReportsRedist2005_x86.msm to your setup project.
The file available at \Program Files\Common Files\Merge Modules
crystal-reports-merge-module-files
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.

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.


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.


sing 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.



5 Tests for Top Performance by Jason Dove

Summary: How to improve the efficiency of any Crystal Report using one or more of the five steps in this article.
5 Tests for Top Performance
It is complete, your masterpiece report. Not only does it meet your customer's expectations, it blows them out the water, all they want is beautifully summarised and displayed in a myriad of ways.
Then
Disaster!
You try to run the report for a month against the live database and not the two days test data you used for development.
Suddenly your report's runtime goes from twenty seconds to two hours.
Every Crystal Reports developer has experienced this situation and it can be one of the most frustrating aspects of report design.
Thankfully there are a variety of things that can be done to combat bad performance, any one of which can reap huge benefits.
Here are the five most likely causes of poor performance and how to mitigate their effects.
1. The Database Set Up
This may or may not be within your direct control to alter, but databases are not set up ideally.
Two top contenders are:
a: The fields you are filtering on are not indexed. You can check whether or not this is the case by referring to the Linking Tab in the Database Expert window. Indexed fields have colored markers next to them.
I have personally seen reports run hundreds of times quicker due to the addition of an index being added to an important (to the report filter) field.
b: Using a view rather than a table to report from can be devastating to a report's performance. This is mainly due to views not having indexes. A view is a collection of tables (much like a basic report) and is often used to simplify data for end users.
The only way to avoid this is to report on the tables which make up the view. Identifying whether the source of a field is a table or a view can be done via the Database Expert as tables and views are listed separately.
Identifying which tables make up a view can be much trickier and you may need the help of the database documentation.
Also, when using Oracle databases, turning off the case sensitive option on queries can really speed up reporting times but may require existing reports to be rewritten.
2.Using the wrong ODBC driver.
ODBC drivers are how Crystal Reports attaches to the database. There is usually a variety of ODBC drivers which will work for any particular make of database and some are better than others.
The only way to really test this is to run the report with all the suitable ODBC drivers and see which is the most efficient.
Experience has taught me that the ODBC driver provided with the software associated to the database is usually the best option.
3.Excessive Use of Sub Reports
Each sub report is like another report accessing the database, and if that sub report is placed in the Detail Section it will run for EVERY record the main report loads. Even if placed in a Group Section the sub report will still be run numerous times.
Report Sections are usually the ideal place to home a sub report as they will only run once. But this still turns one report into two as far as performance is concerned.
The best way to negate the performance issue caused by sub reports is to not use them.
Ninety nine percent of sub reports are not necessary and the same result can be achieved using other methods through grouping, running totals and / or formulas.
4.Table Linking
Anything other than a Link Type of equals ('=') will cause a massive degradation in performance.
The Link Options window (accessible through right clicking on a specific link) will allow any values to be reset.
If there is a need for this time of link, the same result can be achieved through the Group Selection or through formatting (and hiding the unwanted records) once they are loaded into the report.
5. Record Selection
When code for the record selection is written correctly, Crystal Reports will pass all the logic to the database as SQL and only return the data needed.
If the record selection is not written in an SQL friendly way, Crystal Reports will bring back all the data and then filter it locally. This can be drastically slower than when calculated on the database.
Using the Record Selector Expert will guarantee that any filter created will be evaluated on the database and be as efficient as possible.
An additional point which can make a difference in some cases is when the report is scheduled to run. Heavy network traffic or database usage can impact a report's running time.
Working through the above points will enhance the efficiency of your slowly running reports. Building your reports with all this in mind from the beginning will save you redevelopment time later.

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.
csharp-crystal-report-subreport-final
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.
csharp-crystal-report-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.
csharp-crystal-report-link-subreport
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.
csharp-crystal-subreport-design
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;


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();
        }
    }
}

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.
csharp-crystal-report-subreport-final
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.
csharp-crystal-report-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.
csharp-crystal-report-link-subreport
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.
csharp-crystal-subreport-design
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;

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.
csharp-crystal-report-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 ).
csharp-crystal-report-xml-select
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;


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
 

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
csharp-crystal-report-dataset-product
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.
csharp-crystal-report-select-product
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;

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.
 

Dynamic Crystal Reports from C# Application

Usually Crystal Reports generating with pre-defined columns . That is, the fields showing in Crystal Reports are selecting through a wizard at the time of Crystal Report design.
The following program describes how to generate a Crystal Report in C# with dynamic columns at the time of report generation . That is, we are not selecting any column from database table at the time of Crystal Report design. Instead of that we are passing an SQl query string and get the Crystal Report dynamically at runtime in C# . From the following picture you can understand how it works.
csharp-crystal-report-dynamic-column
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 are going to create a Dynamic Crystal Report with the help of Strongly Typed Dataset. Create a new CSharp project and add a Strongly Typed Dataset in the C# Project . Before creating a Strongly Typed Dataset take a look at the detailed tutorial of how to create a C# Crystal Report from Strongly Typed Dataset of previous section .
Hope you understand how to create a C# Crystal Report from Strongly Typed Dataset. Create a new C# project and add a Strongly Typed Datset . Add five columns in the DataTable of Strongly Typed Dataset. Here we are limiting as five column , but you can add any number of column according to your reports requirements.
csharp-crystal-dynamic-column
Next step is to create a Crystal Reports design from the Strongly Typed dataset. You have to add a Crystal Report in your project and select data source as Strongly Typed Dataset. If you don't know how to do this section , refer the previous section of How to create a C# Crystal Report from Strongly Typed Dataset.
csharp-crystal-report-dynamic-table
Select all the column (five) from Strongly Typed Dataset .
csharp-crystal-report-dynamic-column-selection
Click finish button . Then you can see the selected fields in the Crystal Repots . Arrange the fields according to your requirement . 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 .
Select the default form (Form1.cs) you created in CSharp and drag a Textbox , button and CrystalReportViewer control to your form (like in the first picture ).
Here we are going to pass the SQl statements to Crystal Reports at runtime from C# program . For that we have to parse the SQL statement before we passing it to Crystal Reports. So we create a function for parsing SQL statements in the C# program.
Public Function procesSQL() As String
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

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
    {
        CrystalReport1 objRpt = new CrystalReport1(); 

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection cnn ;
            string connectionString = null;
            string sql = null;
            connectionString = "data source=SERVER NAME;initial catalog=crystaldb;user id=USER NAME;password=PASSWORD;";
            cnn = new SqlConnection(connectionString);
            cnn.Open();
            sql = procesSQL();
            SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
            DataSet1 ds = new DataSet1();
            dscmd.Fill(ds, "Product");
            objRpt.SetDataSource(ds.Tables[1]);
            crystalReportViewer1.ReportSource = objRpt;
            crystalReportViewer1.Refresh();
        }

        public string procesSQL()
        {
            string sql = null;
            string inSql = null;
            string firstPart = null;
            string lastPart = null;
            int selectStart = 0;
            int fromStart = 0;
            string[] fields = null;
            string[] sep = { "," };
            int i = 0;
            TextObject MyText ;

            inSql = textBox1.Text;
            inSql = inSql.ToUpper();

            selectStart = inSql.IndexOf("SELECT");
            fromStart = inSql.IndexOf("FROM");
            selectStart = selectStart + 6;
            firstPart = inSql.Substring(selectStart, (fromStart - selectStart));
            lastPart = inSql.Substring(fromStart, inSql.Length - fromStart);

            fields = firstPart.Split(',');
            firstPart = "";
            for (i = 0; i <= fields.Length - 1; i++)
            {
                if (i > 0)
                {
                    firstPart = firstPart + ", " + fields[i].ToString() + " AS COLUMN" + (i + 1);
                    firstPart.Trim();

                    MyText = (TextObject) objRpt.ReportDefinition.ReportObjects[i+1];
                    MyText.Text = fields[i].ToString();
                }
                else
                {
                    firstPart = firstPart + fields[i].ToString() + " AS COLUMN" + (i + 1);
                    firstPart.Trim();

                    MyText = (TextObject)objRpt.ReportDefinition.ReportObjects[i+1];
                    MyText.Text = fields[i].ToString();
                }
            }
            sql = "SELECT " + firstPart + " " + lastPart;
            return sql;
        } 
    }
}

connectionString = "data source=SERVER NAME;initial catalog=crystaldb;user id=USER NAME;password=PASSWORD;";
You have to provide the necessary database information to Connection String.



 

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.
csharp-crystal-report-add-new
Select Dataset from list
csharp-crystal-report-dataset
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 .
csharp-crystal-report-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.
csharp-crystal-report-id-item
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.
csharp-crystal-report-datatable-select
Click Next button and select ID and Item from the datatable1 to right side and click finish.
csharp-crystal-report-datatable-items
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 .






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(); 
        }
    }
}

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 


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.


 

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;


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:
 

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 .
csharp-crystal-report-summay-new
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
csharp-crystal-report-summary-insert
Now you can see @Total is just below the Total field in the report Footer.
csharp-crystal-report-summary-total.GIF
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;



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.

csharp-crystal-report-summary-result
 

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 :
csharp-crystal-formula-designer
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.
csharp-crystal-report-formula-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.
csharp-crystal-formula-editor
Now you can see Total Under the Formula Field . Drag the field in to the Crystal Reports where you want to display Total.
csharp-crystal-report-formula-designer
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;



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.

csharp-crystal-report-formula-final
 

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;


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 .

csharp-crystal-reports-final
 

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.
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 .
csharp-crystal-report-date-parameter
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 .
csharp-crystal-report-date-formula
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;


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["Orderdate"];
            crParameterValues = crParameterFieldDefinition.CurrentValues;

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

            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 date , then you can see the report whose order date is greater than or equal to the entered date.

csharp-crystal-report-date-result


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

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 .
csharp-crystal-report-parameter-integer
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 .
csharp-crystal-report-integer-formula
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;



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(crParameterValues);

            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.

csharp-crystal-report-ineteger-parameter-result


The Crystal Reports showing the result of Product list whose price is greater than 50.