Click here to Skip to main content
Click here to Skip to main content

Crystal Report with DataSet and DataTable using C#

By , 8 Sep 2008
 
add_rpt-5.jpg

Introduction

In my previous article, I described how to create Crystal Report with Oracle Views.
In this article, I am going to demonstrate how to create a Crystal Report with ADO.NET DataTable.

You will find this article very interesting, simple and easy to understand.
This article needs basic knowledge of .NET.

Note: Please vote for this article.

Background

No background knowledge is needed for this article. This article is very simple and just requires very basic knowledge of .NET.
But I recommend reading my previous article as well, though it has no direct relation with this article.

Using the Code

Now enough of theory, we will move to our point.
So here we go... I have created 2 sample tables for this project. Scripts of tables are
as follows, with some sample insert query to have sample data.

create table tbl_project
(
PROJECT_ID NUMBER(4),
PROJECT_NAME  VARCHAR2(150),
GROUP_CODE  NUMBER(2)
)

create table tbl_project_group
(
GROUP_CODE  NUMBER(2),
GROUP_NAME  VARCHAR2(100)
);

insert into tbl_project values(1,'CrystalReportWithOracle',1);

insert into tbl_project values(2,'Ajax Application',2);

insert into tbl_project_group values(1,'windows application');

insert into tbl_project_group values(2,'Web application');

First of all, create a project in Microsoft Visual Studio 2005 and name it CrystalReportWithOracle.

Then create a form as frmMain and add a Crystal report viewer control to this form.
Add a Reference to System.Data.OracleClient.

Step 1: Adding A DataSet and DataTable

Add a DataSet to your Project and name it as myDataSet, as follows:

add_dataset.jpg

Now add a DataTable to myDataSet:

add_data_table-1.jpg

Now add columns to your DataTable as given below in the image.
Your column name and datatype should be the same as that in your database.

add_data_table-2.jpg

Change the datatype of the DataTable columns as shown below:

add_data_table-3.jpg

Now save this DataTable as my_dt.

add_data_table-4_change_name.jpg

Now we have created our DataSet and DataTable. The next step is to create a CrystalReport.

Step 2: Adding A Crystal Report

Add a Crystal report to the project and name it as my_rpt.

add_rpt.jpg

Choose Using the report wizard.

add_rpt-1.jpg

Choose the data source from project data which is my_dataset in our case.

add_rpt-2.jpg

Choose the columns to be displayed on the report.

add_rpt-3.jpg

Add a group by column, if you want.

add_rpt-4.jpg

Now our designing part is complete.

Step 3: Binding Our Report to our DataSource

Below is the C# code to bind our report to the datasource.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OracleClient;
using System.IO;

namespace CrystalReportWithOracle
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            my_rpt objRpt;
            // Creating object of our report.
            objRpt = new my_rpt();

            String ConnStr = "SERVER=mydb;USER ID=user1;PWD=user1";

            OracleConnection myConnection = new OracleConnection(ConnStr);

            String Query1 = "select a.PROJECT_ID,a.PROJECT_NAME,b.GROUP_NAME from 
            tbl_project a,tbl_project_group b where a.group_code= b.group_code";

            OracleDataAdapter adapter = new OracleDataAdapter(Query1, ConnStr);

            DataSet Ds = new DataSet();

            // here my_dt is the name of the DataTable which we 
            // created in the designer view.
            adapter.Fill(Ds, "my_dt");

            if (Ds.Tables[0].Rows.Count == 0)
            {
                MessageBox.Show("No data Found", "CrystalReportWithOracle");
                return;
            }

            // Setting data source of our report object
            objRpt.SetDataSource(Ds);

            CrystalDecisions.CrystalReports.Engine.TextObject root;
            root = (CrystalDecisions.CrystalReports.Engine.TextObject)
                 objRpt.ReportDefinition.ReportObjects["txt_header"];
            root.Text = "Sample Report By Using Data Table!!";

            // Binding the crystalReportViewer with our report object. 
            crystalReportViewer1.ReportSource = objRpt;
        }
    }
}

Points of Interest

My other articles of interest are:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rehan Ahmad Abbasi
Software Developer (Senior) Al-Jazirah Corporation Riyadh KSA
United Arab Emirates United Arab Emirates
Member
I am a Software Engineer having 4 + years of experience in various skill sets.
Proficiency in Asp.net, C#.net, Vb.net, Ado.net, VB 6.0, J2ME, Ajax, Xslt, Xml, Smart Device (Pocket PC 2003), and Oracle.
 
Extensive experience with analyzing, designing, development, and maintenance of Internet, Intranet, Client Server and Object Oriented applications built on .NET Framework (windows and web app.) and VB 6.0.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
SuggestionUsing single dataset for designing report and for displaying data to reportmemberpsafol30 Dec '12 - 0:23 
1. Do Step 1 & Step 2
 
2. (Instead of Step 3) Drag Binding Source form Tool Bar->Data->Binding Source
 
3. Set bindingSource1 properties as
Data Source: Other Data Sources -> Project Data Source -> myDataSet (Added Data Set Name)
Data Member: my_dt (Table Name in Data Set)
 
4. In Form Load Method write
private void frmMain_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dataSet1.emp' table. You can move, or remove it, as needed.
this.empTableAdapter.Fill(this.dataSet1.emp);
//above 2 lines are already present. Just add below line
CrystalReport11.SetDataSource(dataSet1);

}
QuestionHi all this is solutionmemberDevNet845 Sep '12 - 6:23 
hi
please make change
CrystalDecisions.CrystalReports.Engine.TextObject root;
root = (CrystalDecisions.CrystalReports.Engine.TextObject)
objRpt.ReportDefinition.ReportObjects[0];
Instead of "txt_header"
make it [0]
AnswerhimemberHani .Yusuf5 Sep '12 - 6:28 
Thanks
زين والله زين Shucks | :-> Shucks | :->
GeneralMy vote of 4memberDineshnamdev29 Aug '12 - 22:49 
This is good but if follow this there are few problem I faced in the
 

 

 

 
"
CrystalDecisions.CrystalReports.Engine.TextObject root;
//root = (CrystalDecisions.CrystalReports.Engine.TextObject)
// objRpt.ReportDefinition.ReportObjects["txt_header"];
//root.Text = "Sample Report By Using Data Table!!";"
QuestionTwo or more tablesmembersolid200523 May '12 - 23:00 
how do to add dataset that has 2 or more tables
example:
my database has deliverreceipt table
which contains the dr number, address, date
 
and deliverdetails table
which contains the list of items sent
 
------------
or do I have to use inner join??
QuestionWhat is the "txt_header"? I got a Index Out of range exception in this statementmemberOlgaGushiken9 Apr '12 - 12:08 
CrystalDecisions.CrystalReports.Engine.TextObject root;
root = (CrystalDecisions.CrystalReports.Engine.TextObject)
objRpt.ReportDefinition.ReportObjects["txt_header"];
AnswerRe: What is the "txt_header"? I got a Index Out of range exception in this statementmemberDevNet845 Sep '12 - 6:22 
hi
please make change
CrystalDecisions.CrystalReports.Engine.TextObject root;
root = (CrystalDecisions.CrystalReports.Engine.TextObject)
objRpt.ReportDefinition.ReportObjects[0];
Instead of "txt_header"
make it [0]
GeneralMy vote of 5membermrkanepung17 Jan '12 - 22:35 
Thank you for nice acticle Smile | :) )
GeneralMy vote of 5memberaminer1 Jul '11 - 5:04 
Good clear explaination.
Generaldata not displayed in crytsal reportmembersvknair18 May '11 - 21:04 
i am binding cyrtsla report using datatable , but tge report appears blnak even though the datatable has records
 
& the main thing is even in design time i get teh blank format , no records displayed
 

 
if i browse data i am able to see that data , bit when i click Main preview window i dont get the data
GeneralMy vote of 5memberbalavenkatasivaramkumar7 Dec '10 - 19:52 
nice article. I understood very clearly
GeneralMy vote of 3membershebinbackar5 Aug '10 - 7:00 
Only minimal and beginers version
GeneralReport without External Datasetmemberamit.kumar.1311 Nov '09 - 20:02 
Hello Rehan,
 
I find your article really very helping. First of all thanks for that. But I have still two queries:
 
1. What is this code is for :
 
CrystalDecisions.CrystalReports.Engine.TextObject root;
root = (CrystalDecisions.CrystalReports.Engine.TextObject)
objRpt.ReportDefinition.ReportObjects["txt_header"];
root.Text = "Sample Report By Using Data Table!!";
 
when I am adding this code this is giving "IndexOutOfRange Exception". Why it is giving this error?
 
2. I have to add an external Dataset for displaying the report. Can we add DataSet Programatically. I don't want to use this because in some cases I will have to generate temporary columns; which is hard to handel if we already create table in dataset.
 
Hope you are getting my problems. Waiting for your reply.
 
Regards
Amit
GeneralRe: Report without External DatasetmemberSurajMutha22 Feb '11 - 16:51 
its giving same error for me Index out of bound in XP but same application was running properly in Windows 7 I am unable to recognise problem
 
please give some suggesation..
thank you..
Suraj
GeneralDynamically adding columns to datatablememberthiru_586210 Jul '09 - 2:38 
Hi,
The article was very nice.Its absolutely fine.I have one doubt.After adding datatable from the toolbox, we add the columns to the Data table manually. Is it possible to Add coulmns to the datatable dynamically using code ?? I got 1 such requirement.Am developing a module(part of a product), where we dont know the column names of the table in database.So i cant add the columns to the data table during development.So am planning to create the columns of the datatable dynamically.. Is it possible to achieve this ????...
 
I tried adding columns dyanamically using the instance of the datatable.
eg : Dim testDst As myDataSet.myTableDataTable
testDst = New myDataSet.myTableDataTable
 
testDst.Columns.Add("EmpID")
testDst.Columns.Add("Name")
testDst.Columns.Add("Desgn")
testDst.Columns.Add("Company")
 
But am getting a blank report..
Can anyone help me pls...Am new to crystal reports...
GeneralCrystal Reports using data sets and data tablesmembernitin.mail2021 Apr '09 - 23:57 
Hi,
Can any one of you please tell me how to populate a crystal report through the datatables and data sets..
I dont want to use the wizard. I want to code it.
In the above given code it gives error for the my_rpt.
It says it cant find it in the collection.
Please help me out.
Regards.
Nitin
GeneralVery thanksmembertarksiala25 Mar '09 - 17:32 
Very thank about this article, you are help me a lot Wink | ;)
 
=============
Best regards
Tarek Siala
Tripoli - Libya

GeneralCrystal Report with DataSet and DataTable using C# - responcememberRoopangee Tandon22 Oct '08 - 20:04 
Hello,
 
Thanks for the article.However the dataset1 (eg the instance of data set created at design time is not able to load data from the adapter it is becoming null.This is in case of sql.Could you please clarify
 
Roopangee Tandon

GeneralPlease Vote This ArticlememberRehan Ahmad Abbasi3 Sep '08 - 10:45 
Please Vote This Article Smile | :)
 
RAAbbasi

GeneralRe: Please Vote This Articlemembervinod.chakote6 Sep '10 - 0:52 
Very Helpful

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 8 Sep 2008
Article Copyright 2008 by Rehan Ahmad Abbasi
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid