Thursday 1 December 2011

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
 

No comments :