0% found this document useful (0 votes)
148 views21 pages

Crystal Reports

This document discusses how to create Crystal Reports in C# using a dataset as the data source. It describes creating a dataset to retrieve data from a database using a data adapter. It then explains how to create a Crystal Report, select the dataset as the data source, and add fields to the report. Finally, it discusses setting the created report as the source for a CrystalReportViewer control on a form to display the report.

Uploaded by

Vinicio Salas
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
148 views21 pages

Crystal Reports

This document discusses how to create Crystal Reports in C# using a dataset as the data source. It describes creating a dataset to retrieve data from a database using a data adapter. It then explains how to create a Crystal Report, select the dataset as the data source, and add fields to the report. Finally, it discusses setting the created report as the source for a CrystalReportViewer control on a form to display the report.

Uploaded by

Vinicio Salas
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.

Text; using CrystalDecisions.CrystalReports.Engine; //importante esta libreria para que funcione using System.Windows.Forms; namespace proyecto { public partial class Form8 : Form { //mi conexion conexionBD miConexion = new conexionBD(0, "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Application.StartupPath + "\\tubasededatos.MDB"); private static Form8 _Form8 = null; public Form8() { InitializeComponent(); } private void Form8_Load(object sender, EventArgs e) { } private void crystalReportViewer1_Load(object sender, EventArgs e) { //la consulta y conexion OleDbConnection conexion = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;"+ "Data Source=" + Application.StartupPath + "\\tubasededatos.MDB"); CrystalReport1 opt = new CrystalReport1(); //nombre del crystal

//Creo el objeto e instancio el objeto DataSet DataSet objDataSet = new DataSet(); //Establezcon la seleccion de Datos OleDbDataAdapter objAdap = new OleDbDataAdapter("Select idreporte, clave, cantidad,descripcion,precio,fecha From productos", conexion);//consulta //Cargo el Repositorio de Datos objAdap.Fill(objDataSet, "productos");//aqui tu tabla //Muestro los datos en el reporte opt.SetDataSource(objDataSet); crystalReportViewer1.ReportSource = opt

Introduction
This article is about creating Crystal Reports using C#.NET. About two weeks ago, one of my friends asked me for this kind of example. He also searched through the Internet and said that he couldn't find a sample. When I was doing this kind of development, I also looked for samples, but I couldn't find one. Thats why I wrote this article on The Code Project without creating reports separately using Crystal Reports other than using .NET IDE.

Create a Dataset

First you should create a Dataset to get data from the DB. By clicking the Add New Item in the Project menu, you can add a Dataset. A picture of an added Dataset looks like the following window and you can add elements to the Dataset by dragging and dropping elements from the toolbox. This Dataset is used to fill the data, which it gets from the DB by using a query. Because of that, the names of the elements in this Dataset should be equal to the names of the elements in the DB. For an example, this Dataset can fill using the following query. Collapse
String connString = @"Provider=Microsoft.Jet.OLEDB.4.0;_ Data Source=..\\..\\myDB.mdb;User ID=Admin;Password="; OleDbConnection conn = new OleDbConnection(connString); conn.Open(); string query = "SELECT studentID, firstName, lastName, birthDate, _ address, contactNo FROM studentInfo"; OleDbDataAdapter oleDA = new OleDbDataAdapter(query,conn);

Create a Report using Crystal Reports


Now that we have a created Dataset, we can use it to fill the report with data, which we will be getting from the DB. As I mentioned before, you can add a Crystal Report to the project by clicking Add New Item in the Project menu. Then the following window will appear, and you can select your choices and click OK.

The next window looks like the following and you have to select your created Dataset under Project Data, and click Insert Table, then click next.

Then you have to add the field, which you want to display in the report through the following window and click next.

You can also go to other tabs of this window and select/deselect your choices. Use the last tab Style to select the format of the report. You can also type a Report Title here and click finish.

Then your report creation is done by the .NET IDE. If you want to make any changes to the report, you can do so by using the .NET IDE.

Set the Created Report to Display in the Form


Then you have to set a crystalReportViewer in your form to load the report that you created earlier. Moreover, you need to set the report source of this crystalReportViewer component, which falls in the properties panel or you can set the report source by using the code like the following: Collapse
// code to get data from the DB DBConnection DBConn = new DBConnection(); OleDbDataAdapter myDataAdapter = DBConn.getDataFromDB(); // use the created Dataset to fill it with data got // from the DB by using the DataAdapter DataSet dataReport = new DataSet(); myDataAdapter.Fill(dataReport,"myPersonalInfoTable"); // create a new report from the created CrystalReport myDataReport myDataReport = new myDataReport(); // set the data source of the report myDataReport.SetDataSource(dataReport); // set the report source of the created crystalReportViewer // component to the created report

crystalReportViewer1.ReportSource = myDataReport;

Additional Information
You can also create reports using Crystal Reports separately without using the .NET IDE. For that, you have to install Crystal Reports as well, and you should save those reports in a directory. Then you have to set the report source of the crystalReportViewer component to the particular report under your report Directory. For example: Collapse
crystalReportViewer1.ReportSource = @..\Reports\salesReport.rpt;

But a better way is the previous one, because we can get data from the DB according to the inputs, which are done by the user of the Applications. Regarding this article, you can send any questions to [email protected]. I will send you any information that you want for your development.

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

If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#. Generating a Strongly Typed DataSet Here we are using a Strongly Typed Dataset for generating a Crystal Reports from SQL Query string . Before start this section , you can take look at the previous section of how to create a C# Crystal Report from Strongly Typed Dataset. Because here we are using Strongly Typed Dataset for generating Crystal Report from SQL Query string. Here we are generating a report against the Product table . So we are passing the following sql and generating the report sql = "SELECT Product_id,Product_name,Product_price FROM Product"; Create a new C# project and create a new Strongly Typed Dataset from Project - Add New Item Dialogue Box. Add three column in the Strongly Typed Dataset .
Product_id Product_name Product_price

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

Select fields ( Product_id , Product_name , Product_price ) from the next screen and click the finish button. Then you will get the designer screen with the selected fields. If you do not know how to create a dataset , refer the previous section How to create a C# Crystal Report from Strongly Typed Dataset. Now the designing part is over. From the source code we can pass the SQL source code to Crystal Reports. Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form . You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code. using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; Copy and paste the following source code and run your C# project Download Source Code Web apps without coding! Generate data entry and reporting .NET Web apps in minutes, straight from your database. Visually stunning, easy to Print Source Code SpreadsheetGear for ASP.NET and WinForms Excel Reporting, dashboards from Excel charts and ranges, Windows Forms

customize and ready to deploy. Download spreadsheet controls, Excel compatible Now! charting, the fastest and most complete Excel compatible calculations and more.
using using using using using using System; System.Windows.Forms; CrystalDecisions.CrystalReports.Engine; CrystalDecisions.Shared; System.Data; 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.

C# Crystal Reports Export to Pdf There are situations when we want to export Crystal reports to .pdf format programmatically. In these situations we can use ExportOptions for export the Crystal Reports to .pdf format. Also we have to set PdfRtfWordFormatOptions and

ExportFormatType.PortableDocFormat . In the following example you can see how to export a Crystal Reports as a PDF format file in C#. All C# Crystal Reports Tutorial in this website is based on the following database crystaldb. So before you begin this section , please take a look at the database structure of crystaldb - Click Here C# crystaldb If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#. In this section we are using our earlier program step by step tutorial for creating a Crystal Reports from C# for pull data from database to Crystal Reports . Before we start this section take a look at the step by step tutorial for creating a Crystal Reports from C# . Here we are making a Crystal Report from Product table and export the report content to a PDF format file. Select the default form (Form1.cs) you created in C# and drag two buttons (Button1, Button2 ) and a CrystalReportViewer control to your form. You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code. using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; Copy and paste the following source code and run your C# project Download Source Code Dashboards from Excel Charts and Ranges You and your users can design dashboards, reports, charts, and models in Excel rather than hard to learn developer tools and you can easily deploy them with SpreadsheetGear for .NET.
using using using using

Print Source Code Coding is stupid! Generate data entry and reporting .NET Web apps in minutes, straight from your database. Visually stunning, easy to customize and ready to deploy. Download Now!

System; System.Windows.Forms; CrystalDecisions.CrystalReports.Engine; 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()); } } }

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

If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#. In this section we are using our earlier program step by step tutorial for creating a Crystal Reports from C# for pull data from database to Crystal Reports . Before we start this section take a look at the step by step tutorial for creating a Crystal Reports from C# . Here we are generating a Crystal Report from Product table and export the report content to an Excel format file. Select the default form (Form1.cs) you created in C# and drag two buttons (Button1, Button2 ) and a CrystalReportViewer control to your form. You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code. using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; Copy and paste the following source code and run your C# project Download Source Code .NET Database Apps in Minutes! Generate data entry and reporting .NET Web apps in minutes, straight from your database. Visually stunning, easy to customize and ready to deploy. Download Now!
using using using using

Print Source Code SpreadsheetGear for ASP.NET and WinForms Excel Reporting, dashboards from Excel charts and ranges, Windows Forms spreadsheet controls, Excel compatible charting, the fastest and most complete Excel compatible calculations and more.

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

namespace WindowsApplication1 { public partial class Form1 : Form { ReportDocument cryRpt; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { cryRpt = new ReportDocument(); cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

crystalReportViewer1.ReportSource = cryRpt; crystalReportViewer1.Refresh(); } private void button2_Click(object sender, EventArgs e) { try { ExportOptions CrExportOptions ; DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions(); ExcelFormatOptions CrFormatTypeOptions = new ExcelFormatOptions(); CrDiskFileDestinationOptions.DiskFileName = "c:\\csharp.net-informations.xls"; CrExportOptions = cryRpt.ExportOptions; CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile; CrExportOptions.ExportFormatType = ExportFormatType.Excel; CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions; CrExportOptions.FormatOptions = CrFormatTypeOptions; cryRpt.Export(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }

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.

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.

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.

Select all the column (five) from Strongly Typed Dataset .

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; Copy and paste the following source code and run your C# project Download Source Code Customized Reporting Apps! Print Source Code SpreadsheetGear: ASP.NET Excel

Build database and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!
using using using using using using

Reporting Easily create richly formatted Excel reports without Excel using the new generation of spreadsheet technology built from the ground up for scalability and reliability. learn more

System; System.Windows.Forms; CrystalDecisions.CrystalReports.Engine; CrystalDecisions.Shared; System.Data; 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.

Codigo Buenaso

private void btnReporte_Click(object sender, EventArgs e) { try { //Creamos el documento CrystalDecisions.CrystalReports.Engine.ReportDocument rpt=new CrystalDecisions.CrystalReports.Engine.ReportDocument(); //Obtenemos el documento que se encuentra en nustra carpeta bin\debug\crReporte.rpt rpt.Load( Application.StartupPath + "\\crReporte.rpt");

//Lleanamos el reporte con la informacin que obtenemos de la base de datos rpt.SetDataSource(NegVenta.ObtenerVenta(Convert.ToInt32(this.txtCodigo Venta.Text))); //Establecemos los datos al reporte this.crvReporte.ReportSource=rpt; //Refrescamos nuestro reporte this.crvReporte.RefreshReport(); } catch (Exception ex) { } }

You might also like