Thursday, 1 December 2011

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.
 

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)
csharp-crystal-report-field-explorer
Then you can see Field Explorer in the Left hand side.
Select Parameter Field from Field Explorer and right Click on Parameter Field.
csharp-crystal-report-parameter
Fill the appropriate name for Name and Prompting text fields like the following picture.
csharp-crystal-report-fill-parameter
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 .
csharp-crystal-report-selection-formula.GIF
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.
csharp-crystalreport-make-formula
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 .
csharp-crystal-report-parameter-viewer
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["Customername"];
            crParameterValues = crParameterFieldDefinition.CurrentValues;

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

            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.

csharp-crystal-report-string-final


Here we get the result of the Customer4's order details.
 

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.
csharp-crystal-reports-multiple-tables
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 .
csharp-crystal-report-multiple-tables-relations
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 .
csharp-crystal-report-field-selection.GIF
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.
csharp-crystal-report-designer-multi-tables
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 .
csharp-crystal-reports-viewer
After you drag the CrystalReportViewer to your form , it will look like the following picture.
csharp-crystal-reports-form
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;





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.

csharp-crystal-reports-multi-table-show.GIF


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 -
 

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.
csharp-crystal-reports-1.GIF
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.
csharp-crystal-report-add-newitem
Select Report type from Crystal Reports gallery.
csharp-crystal-report-gallary
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 .
csharp-crystal-reports-oledb
Select Microsoft OLE DB Provider for SQL Server .
csharp-crystal-reports-oledb-provider
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 .
csharp-crystal-reports-oledb-authentication
Click next , Then the screen shows OLE DB Property values , leave it as it is , and then click finish button.
csharp-crystal-reports-oledb-finish
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.
csharp-crystal-reports-product
Click Next Button
Select all fields from Product table to the right side list .
csharp-crystal-reports-all-tables
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.
csharp-crystal-report-designer-window
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 .
csharp-crystal-reports-viewer
After you drag the CrystalReportViewer to your form , it will look like the following picture.
csharp-crystal-reports-form
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;



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. 





   
csharp-crystal-reports-final


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 - C# Dynamic logon parameters in Crystal Reports.

Hope this tutorial help you to create your first Crystal Reports in C#.
 
 

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 :
csharp-crystal-report-table-relations
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
csharp-crystal-report-ordermaster-data
Order Details Table Data
csharp-crystal-report-orderdetails-data
Product Table Data
csharp-crystal-report-product-data