Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Crystal Reports » Creating Reports in C# using Crystal Reports with Xml data Definitions

Creating Reports in C# using Crystal Reports with Xml data Definitions

This article explains how to extract data into a Crystal Report created outside a C# project using xml data definitions and data sets.

Technologies: Crystal Reports,Visual C# .NET
Total downloads :
Total page views :  55717
Rating :
 5/5
This article has been rated :  4 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
ArticleAd
Become a Sponsor



Abstract

This article explains how to extract data into a Crystal Report created outside a C# project using xml data definitions and data sets.

Introduction

This requirement was a part of a main C#.net project, where we wanted to develop reports using crystal reports using field definitions. As we took a great deal of effort in arriving at a solution, and information available in the C# corner helped us to a great extent, we decided to submit this code 
for the benefit of the fellow programmers.

In this project,

  • The report is formatted outside the project via Crystal Reports (the .rpt file)
  • The data to the report is extracted from a field definition file created as a .xsd extension (as compatible with ADO.Net)
  • The report is called and displayed through a form using the crystal report viewer.

The example overview

We have taken the Authors table in the pubs database where au_id, au_lname, au_fname will be printed on the report.

The main requirement is to create the Xml schema file with .xsd extension and bind the data to the .rpt file.

The example handles this in one form with two buttons: The XSD Button to create the .xsd field definition file and the VIEW button to generate the report.

So here is the step by step procedure to arrive at this.

1. Create the .xsd field definitions file depending on the data that we want to extract from a database.

Insert the following code in the click event of  XSD  button, to create the .xsd file. In our example this file is called the 'sampledatadef.xsd'. This is created in c:\

By inserting the following code into the start form of your project and clicking the XSD button, you will see the sampledatadef.xsd created in the root directory of your c:\

// References used
using System;
using
System.Drawing;
using
System.Collections;
using
System.ComponentModel;
using
System.Windows.Forms;
using
System.Data;
using
System.Data.SqlClient;
// These are auto generated
private
System.Windows.Forms.Button button1;
private
System.Windows.Forms.Button button2;
private System.ComponentModel.Container components = null
;
///
<summary>
///
This is to generate the field definition file
///
This code needs to be executed, only when there had been a change to the
///
Data fields that are to be extracted.
///
</summary>
private void button1_Click(object
sender, System.EventArgs e)
{
SqlConnection mcon_pub;
SqlDataAdapter mda_fld;
// Remember to change data source as applicable.
string
constr = "Data source =SERVER;Initial catalog=pubs;User ID=sa;password=";
string
sqlstmt = "select au_id, au_lname, au_fname from Authors";
DataSet ds_fldDef =
new
DataSet();
mcon_pub =
new
SqlConnection(constr);
mda_fld =
new
SqlDataAdapter(sqlstmt,mcon_pub);
ds_fldDef =
new
DataSet();
mda_fld.Fill(ds_fldDef);
ds_fldDef.WriteXmlSchema(@"c:\sampledatadef.xsd");
MessageBox.Show ("Field Definitions Written Successfully");
}
private void button2_Click(object
sender, System.EventArgs e)
{
ViewReport mfrm_view =
new
ViewReport();
mfrm_view.Show();
}

2. Now create the .rpt file in crystal reports using the .xsd field definitions file.
You need to select 'Create new Connections' and take option - Field Defintions. Select the ADO.NET option. In the dialogue box you will be asked to enter the xsd file name. Select the path and click the 'Finish' button.

We have named this report as crystalsample.rpt (saved in c:\)

If the ADO.Net option is not available, you will have to add new components to the installed crystal reports using 'Add/Remove' programs option and include the necessary component to the Crystal Reports installation.

3. Generate the class to hold the data set for the .xsd datadefiniton
This is an important step. The .xsd definitions do not recognize the datasets generated through the normal DataSet class. The report will be displayed only with the headings, if this step is not accomplished!!! (This was a weird experience to us).

This is done though executing the following command through the command prompt tool of the Visual Studio .Net Tools.

xsd.exe /d /l:C# sampledatadef.xsd

(The /d directive tells the tool to generate DataSets, /l specifies the language to use)

This command generates the DataSet class compatible with the .xsd file you created in the path in which you executed the command. The name of the source file will be sampledatadef.cs.

4. Now add this class to your project.
In the source file, the name of the class will be generated as 'NewDataSet'. Rename this name to a name that you desire in the source file. We have named it as ds_SampleDataSet

5. Now generate the code to extract the data from field definition
In our example we have used a new form for this, which is loaded with the click event of the VIEW button.

This is done in an easy set of steps.

  1. Define a dataset of the newly generated type. In this example
    Private ds_sampledataset mydataset = New ds_sampledataset()
  2. Fill this dataset with the identical data fields that you created for the xsd definition file. In this example they are au_id, au_lname, au_fname of Authors. 
  3. Open a new ReportDocument type class and call the .rpt file you created into it. (Make sure that the necessary references are added to the project - CrystalDecisions.CrystalReports.Engine CrystalDecisions.Shared )

The form to load the report is named as ViewReport and the CrystalReportViewer is added to the form

The essential coding to the form goes as follows:

// References used
using System;
using
System.Drawing;
using
System.Collections;
using
System.ComponentModel;
using
System.Windows.Forms;
using
System.Data;
using
System.Xml;
using
System.Data.SqlClient;
using
CrystalDecisions.CrystalReports.Engine;
using
CrystalDecisions.Shared;
// private variables defined
private
SqlConnection mcon_pub;
private
SqlDataAdapter mda_Rpt;
private ds_SampleDataSet ds_xml = new
ds_SampleDataSet();
// These are auto generated
private
CrystalDecisions.Windows.Forms.CrystalReportViewer crystalReportViewer1;
private System.ComponentModel.Container components = null
;
///
<summary>
///
Connects to the database and extracts data into the new dataset type class
///
</summary>
private void
SetConnection()
{
string
sqlstmt = "select au_id, au_lname, au_fname from Authors";
// Remember to change data source as applicable.
string constr = "Data source =SERVER;Initial catalog=pubs;User ID=sa;password=";mcon_pub = new
SqlConnection(constr);
mda_Rpt =
new
SqlDataAdapter(sqlstmt,mcon_pub);
// Note that the data is filled into the new xml type
datasetmda_Rpt.Fill(ds_xml);
}
private void
SetReport()
{
ReportDocument rpt =
new
ReportDocument();
rpt.Load(@"C:\crystalsample.rpt");
rpt.Database.Tables[0].SetDataSource(ds_xml);
crystalReportViewer1.ReportSource = rpt;
}
///
<summary>
///
The load event of this form is named as Form1_Load
///
</summary>
private void Form1_Load(object
sender, System.EventArgs e)
{
SetConnection();
SetReport();
}

References : 


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Krishnajina
Krishnajina is BSc Honors Graduate From University of Colombo,Sri Lanka and a MBCS (Member British Computer Society). She has more than 15 years experience in software design development and implementation. Charith is a Diploma Holder of the National Institute of Business Management (NIBM) Sri Lanka, and is into development.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Thanks!! It was driving me crazy!!David8/31/2007
Thanks for this article - I was tying to used stored procedures to create a report and this helped immediately!!!!!
Reply | Email | Delete | Modify | 
yes all OK but...Bianca12/11/2007
My report in this way is perfect, but when I click a Crystal Report Button Print to produce the .pdf file, my .pdf is empty. Have you some solution? Thank's :) Bianca from Italy
Reply | Email | Delete | Modify | 
nice workSusan12/18/2008
I found this quite helpful. Thank you! --Susan
Reply | Email | Delete | Modify | 
Crytal Report Date Format ProblemAbdulla3/27/2009
This article is Excellent, but i am having a problem that i am not able to do Date Formatting in crystal report. i selected 'Format Object' from right click popup menu and i 've chosen a custom format, but it doesn't work. it shows format '2009-01-02 T 00:0000' like this at run time. How can i correct this. Can any one help me out on this issue please ? Thank you in Advance.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved