Integrating Crystal Reports in .NET using C#






3.09/5 (13 votes)
An article on integrating Crystal Reports in .NET using C#

Introduction
This article is aimed at users who want to embed Crystal reports in Windows based .NET applications using C#.
Using the Code
Embedding Crystal Reports in a Windows based application goes through easy steps:
-
Add your report name in the reports combo:
-
Apply your criteria:
// // show the controls that create the report criteria // hideAll(); if(reportChoose.SelectedIndex==1) { cmbCriteria.Visible=true; lblCriteria1.Visible=true; Choose.Size = new Size(224, 208); ShowReport.Location = new Point(40, 168); lblCriteria1.Text = "From Country:"; dbutil.fillCombo(cmbCriteria, "select country from employees group by country"); cmbCriteria.Items.Insert(0,"All Countries"); cmbCriteria.SelectedIndex = 0; } else if(reportChoose.SelectedIndex==2) { }
So we have this:
-
Create XML based on your data to create a report depending on it:
// // view report action // crvReport.ReportSource = null; this.Cursor = Cursors.WaitCursor; if(reportChoose.SelectedIndex==1) { string sql = "select * from employees"; if(cmbCriteria.SelectedIndex!=0)// show all employees { sql+= " where country='"+cmbCriteria.Text+"'"; } WriteSchemaFile(sql); } this.Cursor = Cursors.Default; System.GC.Collect();
This will create an XML file on the local drive C: (wait... it is not a fixed path report, it will be dynamic soon) called data.xml.
// // WriteSchemaFile method // private void WriteSchemaFile(string SQL) { OleDbDataAdapter da = new OleDbDataAdapter(SQL, dbutil.con); DataSet ds = new DataSet("data"); da.Fill(ds, "dataTable"); ds.WriteXml("c:\\data.xml", XmlWriteMode.WriteSchema); }
-
Create a report based on the XML file:
-
Add a new report:
-
Choose XML data source:
-
Locate file:
- Click Finish.
-
This is the unformatted version of the report.
After formatting:
//
// view report action
//
crvReport.ReportSource = null;
this.Cursor = Cursors.WaitCursor;
if(reportChoose.SelectedIndex==1)
{
string sql = "select * from employees";
if(cmbCriteria.SelectedIndex!=0)// show all employees
{
sql+= " where country='"+cmbCriteria.Text+"'";
}
//WriteSchemaFile(sql);
reports.employees emp = new CRElegantViewer.reports.employees();
emp.Database.Tables[0].SetDataSource(getDataSet(sql));
crvReport.ReportSource = emp;
crvReport.Visible=true;
tools.IsExpanded = true;
}
this.Cursor = Cursors.Default;
System.GC.Collect();
//
// get DataSet Method
//
private DataSet getDataSet(string SQL)
{
OleDbDataAdapter da = new OleDbDataAdapter(SQL, dbutil.con);
DataSet ds = new DataSet("data");
da.Fill(ds, "dataTable");
return ds;
}
So now, you don't need the XML file anymore.
Have fun!