Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » Crystal Reports C# » Generating a Report from Multiple Data Sources in Crystal Reports

Generating a Report from Multiple Data Sources in Crystal Reports

If you have to create a report in Crystal Reports from multiple data sources or provide multiple views of the data, you may find sticky situations because CR does not allow you to have multiple Detail sections in a single report.

Author Rank :
Page Views : 126688
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

If you have to create a report in Crystal Reports from multiple data sources or provide multiple views of the data, you may find sticky situations because CR does not allow you to have multiple Detail sections in a single report. For example, say you have to display data from two tables on the same report page. Now say, you create two Detail sections and bind each Detail section with a table, you will find second table records repeating within the first table records. 

For example, if I want to generate a report that looks like Figure 1.

Report Header
  - Page Header
       o Detail - Data from Customers table
       o Detail - Data from Orders table
  - Page Footer
Report Footer

Figure 1.

To do this, you will have to create two details sections on the same level, not recursive.

The work around for this is using sub reports. What we do is to create two sub reports, one for Customers and one for Orders. These sub reports have nothing but a single Detail section.

Now we create two Page Header sections on the main report and put a sub report on each Page Header sections. The new report looks like Figure 2.

Report Header
  - Page Header 1
      o Sub Report 1
  - Page Header 2
      o Sub Report 2
      o Detail Section (Hide it)
  - Page Footer
Report Footer

Figure 2.

In the above format in Figure 2, we treat each sub report as a separate report. Now you can bind each sub report with a separate DataSet or DataTable. 

For example, if we have data coming in a DataSet from two tables-Customers and Orders, the following code binds each DataTable to a separate sub report: 

Dim report As New DynamicReport
report.SetDataSource(ds)
report.Subreports.Item("SubReport1").SetDataSource(ds.Tables("Customers"))
report.Subreports.Item("SubReport2").SetDataSource(ds.Tables("Orders"))
CrystalReportViewer1.ReportSource = report
CrystalReportViewer1.DataBind()

Similarly, your data can be coming from multiple data sources; you can bind as many as sub reports with different data sources.

Note: In the above code, DynamicReport is the class name of crystal report. For example, if you have a crystal report called "MyReport.rpt" and you add this report to the VS.NET project, you will see a class "MyReport.cs" or "MyReport.vb" depending on the language you choose. Make sure you change DynamicReport with your class name "MyReport".

Summary

In this article, we learned how to create multiple sub reports and bind them with multiple data source using DataSet. Using the same approach, you can get data from multiple data sources in a single report.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
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.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Can't find report 'DynamicReport' by Sarim On October 21, 2006

Can you please tell me which name space or DLL i have to add in my project to find 'DynamicReport' class. i m using CR 10, and current i m using these three namespaces in my project.  

using CrystalDecisions.Shared;
using CrystalDecisions.Web;
using CrystalDecisions.CrystalReports.Engine;

but when i try to use your code i can't find 'DynamicReport' what you use in your Code.

 

 

 

Reply | Email | Modify 
Re: Can't find report 'DynamicReport' by Mahesh On October 21, 2006
DynamicReport is a report you created using VS.NET or Crystal Report. If you create a .cr file, you would see a class for that .cr file. For example, if you add a Crystal Report file using VS .NET called ABC, a class ABC.vb or ABC.cs (depending on the language) will be added to your project. So you will replace DynamicReport with ABC.
Reply | Email | Modify 
vikram by vikram On November 28, 2006

i am using VS 2003 and i could not find the property called

Subreports.Item

Reply | Email | Modify 
Re: vikram by Mahesh On November 29, 2006

I am using VS 2003 also but also have CR 10 installed.

VS 2003 uses CR 9.0 by default and it is possible Report class does not have that property but there should be something similar.

Reply | Email | Modify 
Can i ask for other examples.. by Edmond On January 26, 2007
hi.. this is edmond. can i ask other examples...
Reply | Email | Modify 
Re: Can i ask for other examples.. by Mahesh On January 29, 2007

Crystal Reports section has more example. Click on Crystal Reports in the left side menu or go from Technologies menu.

Do you need any specific sample?

Reply | Email | Modify 
Re: Re: Can i ask for other examples.. by Srinivasa Rao On February 19, 2007

Hi Mahesh,

follow line doesn't work in VS2005(C#.Net).

report.Subreports.Item("SubReport1").SetDataSource(ds.Tables("Customers"))

Could You tell me what is the equal command in VS2005

thanks and regards

Srini

Reply | Email | Modify 
Re: Re: Re: Can i ask for other examples.. by Mahesh On February 20, 2007

Srini,
Make sure your report has a sub report called "SubReport1" and your DataSet should also have a DataTable named "Customers". If you are getting data from the database and filling it direct, use "ds.Tables(0)" instead, which will return first table no matter what the table name is.

Reply | Email | Modify 
Re: Re: Re: Re: Can i ask for other examples.. by Srinivasa Rao On February 20, 2007

I face following problem

(1)report.Subreports after that I am not getting "Item" keyword

Yes Report had SubReports name "SubReport1"

Reply | Email | Modify 
Re: Re: Re: Re: Can i ask for other examples.. by Srinivasa Rao On February 20, 2007
I forgot to tell to you. I am using CrystalReports XI with C#.Net 2.0
Reply | Email | Modify 
Re: Re: Re: Can i ask for other examples.. by marshall On May 23, 2007

marshall_martin@bcbstx.com

I use this and I can set the sub report datasource but the problem it says that it cannot find my parameters in my sub reports.

 crLtr_New.Subreports.Item("ltrIneligiblewithSum.rpt").SetDataSource(Me.DsAll1.Tables("dbo_usp_WS_RACI_Summary_Reports"))
        'crLtr_New.SetParameterValue("prmRACI", Me.DsAll1.Tables("dbo_get_ineligible_with_sum").Rows(0)("group_raci"))
        'crLtr_New.SetParameterValue("prmAddr_Ln1", Me.DsAll1.Tables("dbo_get_ineligible_with_sum").Rows(0)("addr_ln_1"))
        'crLtr_New.SetParameterValue("prmAddr_Ln2", Me.DsAll1.Tables("dbo_get_ineligible_with_sum").Rows(0)("addr_ln_2"))

Hope it helps,
MECCA

Reply | Email | Modify 
Can i ask for by Amal On November 20, 2007
I want to ask how can i write a query in Crystal Reports in C# .net 2003,not make the report by wizard thanks
Reply | Email | Modify 
Using Grouping on actual report with sub reports by James On February 20, 2007
we are pulling data from 2 sub reports in page header, however we'd like to group on the actual report at the same time. Can this be done? If so how?
Reply | Email | Modify 
need your help by Mony On April 23, 2007
Hi, Pls can you show me how to pass few parameters from form1 to form2(Report) in VB 2005? I am a new developer. Thanks ssmony@gmail.com
Reply | Email | Modify 
Re: need your help by Mahesh On April 24, 2007
If you click on Crystal Reports section of this site in the left side, you will see articles on "How to pass parameters in a Report".
Reply | Email | Modify 
Help To Create Reports by Kartheek reddy On June 20, 2007
Hai Mahesh, I am Kartheek, http://www.codeproject.com/useritems/Le_Quang_Anh.asp using the above link I have created Reports successfully. But Now I have to generate a Report Using two datasets as created in the above example in the site. I tried that using ur example but I amnot able to do that... so can u plz help to Generate a single report using two or more datasets as shown in the above example.
Reply | Email | Modify 
Re: Help To Create Reports by Mahesh On June 26, 2007

Yes you can generate a report from two DataSets. The simplest way for this would be you Merge two DataSets in your code and to the report you actually be passing only a single DataSet object.

Check out DataSet.Merge method.

Reply | Email | Modify 
David Perales by David On June 20, 2007
Hi. i'm from Peru, your site is very great, i have a problem with the report.. ' cant see the property subreports. i'm using the 9.0 version, can you tell how can i get the upgrade? or i have any other option? thanks.
Reply | Email | Modify 
Re: David Perales by Mahesh On June 21, 2007
Hmm .. I am not sure unless it's a property in version 10 only. For that, you have no choice but to upgrade it to version 10.
Reply | Email | Modify 
crystal report by Praveen On July 23, 2007
hai nahesh this is praveen i am geting a problem when i am viewing a crystal report in run time using c# .net field values are repeated please solve the problem as possible as immediately +91 9885348542
Reply | Email | Modify 
Re: crystal report by Mahesh On July 23, 2007
Not sure Praveen if I understood your question. Try exploring more articles in Crystal Reports section on how to create reports dynamically.
Reply | Email | Modify 
subreports showing on top of each other by wael On July 30, 2007
I am using crystal reports 8.5 I have a report that has 2 subreports in it. I placed the subreports under each other but the problem is that when I preview the report, the data from subreport one come over the data from subreport two. If I put the subreports far from each other and subreport one has few records then there will be a big space. Is there a way to solve this dynamically??
Reply | Email | Modify 
hi by Jeya On August 20, 2007

i am using VS 2003 and i could not find the property called

Subreports.Item

Could You tell me what is the equal command

thanks and regards,

Jeya.

Reply | Email | Modify 
Re: hi by Mahesh On August 20, 2007

Have you created an instance of your report class you added using VS 2003? Say your report is, JeyReport.rpt, you have to do something like this:

JeyReport jr = new JeyReport();

Then you can access SubReports property using jr.SubReports

Reply | Email | Modify 
Re: hi by Rob On August 20, 2007
Please excuse duplicate listings.  The system posted them on page refresh and will not let me delete.  My apologies.
Reply | Email | Modify 
no subreport.item by Rob On August 20, 2007
I'm using CrystalReports .NET 2005 also and don't have Item as a recognized option in the intellisense. I notice the reports I create don't have code-behind .cs files. Could this be the reason for the difference? Can you suggest a workaround? Thanks so much.
Reply | Email | Modify 
no subreport.item by Rob On August 20, 2007
I'm using CrystalReports .NET 2005 also and don't have Item as a recognized option in the intellisense. I notice the reports I create don't have code-behind .cs files. Could this be the reason for the difference? Can you suggest a workaround? Thanks so much.
Reply | Email | Modify 
no subreport.item by Rob On August 20, 2007
I'm using CrystalReports .NET 2005 also and don't have Item as a recognized option in the intellisense. I notice the reports I create don't have code-behind .cs files. Could this be the reason for the difference? Can you suggest a workaround? Thanks so much.
Reply | Email | Modify 
Re: no subreport.item by Mahesh On August 23, 2007
Yes, that's the reason. You should have the code behind file. Try to remove and add it again report using Add Existing Item option.
Reply | Email | Modify 
Using two subreports.Showing Error. by sree On September 11, 2007
I am using two subreports.In the local mahcine it's worked well.But in the live machine its showing the error that 'An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) '. What's the solution for this error. Need help immediatly.
Reply | Email | Modify 
Re: Using two subreports.Showing Error. by Mahesh On September 11, 2007

The error has nothing to do with the number of subreports. It seems like problem is in your connection. If you are using hardcoded SQL Server connection in your report, check that out. There is nothing much I can tell you.

Reply | Email | Modify 
Re: Re: Using two subreports.Showing Error. by sree On September 12, 2007

Thanks for ur advice.

It's because of some connection problem.

Now it's working well.

 

Reply | Email | Modify 
Report.Subreports.Item gives error in 2003 by santosh On October 9, 2007

follow line doesn't work in VS2003 using VB.NET report.Subreports.Item("SubReport1").SetDataSource(ds.Tables("Customers")) Could You tell me how i can use it?

I have created object of report like below but still same problem

JeyReport jr = new JeyReport();

thanks and regards Santosh

Reply | Email | Modify 
Report.Subreports.Item replace with.. by Leo On November 16, 2007

Hi.

Even I was facing the same problem. I did it this way to overcome the issue.

ReportDocument rpt = new ReportDocument();

rpt.Load(strApplicationPath + @"\rptMultiple.rpt");

rpt.SetDataSource(ds);

rpt.Subreports["rptMultiple_1.rpt"].SetDataSource(ds.Tables[0]);

rpt.Subreports["rptMultiple_2.rpt"].SetDataSource(ds.Tables[1]);

CRViewerMultiple.ReportSource = rpt;

where rptMultiple.rpt is the main report and rptMultiple_1.rpt and rptMultiple_2.rpt are two subreports. You can even use the index of the subreport as follows:

rpt.Subreports[0].SetDataSource(ds.Tables[0]);

Now, run the main form, you will be able to view the report, but if you click on the data, it will drildown to the subreports. In order to overcome that, go to the windows/web form, change the crystalreportviewer's 'EnableDrilDown' property to False.

Hope someone will find this useful.

Regards,

Leo.

 

Reply | Email | Modify 
Getting an error while paging by Chockalingam On November 20, 2007

Hi Mahesh,

When the page loads for the first time it works fine and then when I click the next page it gives the error "The communication channel has not been created" while assigning the datasource for the subreport. (myReportDoc.Subreports[0].SetDataSource(dataSet.Tables[1])). Any idea?

I am using Crystal Reports which comes with VS 2005.

Thanks Chocks

Reply | Email | Modify 
Re: Getting an error while paging by Mahesh On April 6, 2009
I am not sure. Did you try posting your question on forums? May be somebody knows the answer.
Reply | Email | Modify 
Hello I need your help by Khamphouvieng On December 18, 2008
I have read this article, but I still don't know how to display data from multiple tables. In my project i have used more than 2 tables with no relation between them. I want the data from Table(N) displays after the data from Table(N-1) with the same page header (Because the tables have the same column name). So please help me Best Regards Thanks!
Reply | Email | Modify 
Re: Hello I need your help by Mahesh On April 6, 2009
If columns are same, its simple.
In your code you get data from first table in DataSet1 and get data from second table in DataSet2. Then call DataSet1.Merge(DataSet2) and you will have all data in one DataSet. Then you bind your report with DataSet1.
Reply | Email | Modify 
Error while filling the crytal report with two or more dataset by Kapil On June 1, 2009
I have same requirement accept I requires three page header section as in First section I required to write company name and its address and other details and also I do in Asp.Net 2.0 with the help of the XSD file. I file the XSD file with the dataset and XSD is bind with the crystal report.
And after that i required to show two reports with their individual totals and after that I required the grand total. I try the solution which you discuss in this articles 
but unfortunately It gives error "The page size was not large enough to format the contents of an object in the report. Error in File C:\DOCUME~1\kapil\LOCALS~1\Temp\PolicyStatusreport {0E96C854-3FDE-4C82-8A01-C15F9A7138C7}.rpt: Page header or footer longer than a page".
My requirement is some what like.

Report Header
  - Page Header 1
      Static Data
  - Page Header 2
      Sub Report 2
  - Page Header 3
      Sub Report 3
      Detail Section (Hide it)
-------------------------------------------------> After data I required the "Grand Total" which is the sum of the total of the two individual reports.
  - Page Footer
Report Footer


Please give me some suggestions to sort out this error. I will be very thanks full to you.
Reply | Email | Modify 
Re: Error while filling the crytal report with two or more dataset by Catinca On March 18, 2010
Only in Report Header you can have all pages of the subreport.
Reply | Email | Modify 
Error while filling the data with two dataset in the crystal report by Kapil On June 1, 2009

Hi Mahesh,
I have same requirement accept that I do the same thing in Asp.net 2.0 with the XSD file. I fill the XSD file with the dataset and XSD is bind with the crystal report. I requires three page header section as in First section I required to write company name and its address and other details and then the two page header sections for the two sub reports.
And after that i required to show two sub reports with their individual totals which I am doing in the same individual sub report and after that I required the grand total. I try the solution which you discuss in this articles but unfortunately It gives error "The page size was not large enough to format the contents of an object in the report. Error in File C:\DOCUME~1\kapil\LOCALS~1\Temp\PolicyStatusreport {0E96C854-3FDE-4C82-8A01-C15F9A7138C7}.rpt: Page header or footer longer than a page".
My requirement is some what like.

Report Header
  - Page Header 1
      Static Data
  - Page Header 2
      Sub Report 2
  - Page Header 3
      Sub Report 3
      Detail Section (Hide it)
-------------------------------------------------> After data I required the "Grand Total" which is the sum of the total of the two individual reports.
  - Page Footer
Report Footer


Please give me some suggestions to sort out this error.

Reply | Email | Modify 
Multiple Data Source in CR by Liz On August 12, 2009
Thank you for your article. It is so hard to find comprehensive information about Crystal Reports.
Reply | Email | Modify 
error in dynamic crystal report by asm On September 7, 2009
please help me as i am not getting data in crystal report using stored procedure
my code is as
 Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("satinconnectionstring").ConnectionString)
        con.Open()
        Dim cmd As New SqlCommand
        cmd.Connection = con
        Dim dat As Date = Today.Date
        Dim M As Int16 = Today.Day
        If M >= 28 Then
            M = 28
        End If
        Dim W As String = Today.DayOfWeek.ToString
        cmd.CommandText = "EXEC MYSP_DEMAND_SHEET '20983','" & M & "','" & W & "','" & dat & "'"
Dim da As New SqlDataAdapter(cmd.CommandText, con)
        Dim ds As New DataSet
da.Fill(ds)
Dim myReportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument
        myReportDocument = New CrystalDecisions.CrystalReports.Engine.ReportDocument()
        myReportDocument.Load(Server.MapPath("CrystalReport2.rpt"))
 myReportDocument.Database.Tables(0).SetDataSource(ds)

        CrystalReportViewer1.ReportSource = myReportDocument
        CrystalReportViewer1.DataBind()
please help me in this regard
Reply | Email | Modify 
Only the Report Header prints if one of the subreports exceeds 1 page. by joshua On October 8, 2009
Thanks for the informative article. 

I set up my report like you specified and it prints fine if the report doesn't exceed 1 page.  I hid the Details section and set Section 2 and PageHeaderSection2 to NewPageBefore = true, but that didn't help.

Do you have any ideas?  Thanks.
Reply | Email | Modify 
Multiple Data Sources in Crystal Report by Catinca On March 18, 2010
Hi,
Can somebody explain how to generat a report using 2 different database? I will realy appreciate.

Cathy.
Reply | Email | Modify 
fdgdfg by zohaib On May 9, 2010
dfgfgf
Reply | Email | Modify 
How to set dataset programatically to crystal report with multiple tables by minakshi On May 11, 2010
Hi Mahesh ,
In my application I have two tables bill & bill details which data  i want to display using crystal report. Tables are linked with the foreign key relation. How can I do this?
 Thanks,
Minakshi.
Reply | Email | Modify 
Report Binding Through Stored Pro. by Harmeet On July 15, 2010
Hi This Is  a Great site and i have some serious trouble.
i am trying to bind my report through stored procedure as it is not getting connected to the SQL  server (its not showing the server and database name ) so i created a stored proc binding many tables its working fine ..i am able to preview data in dataset but not in the report i have added the fields and the parameter but its not working .

plz help me out as i m new to this.
Reply | Email | Modify 
crystal report prompts for db login in infview while refreshin the report by preeti On August 6, 2010
Hi,

I have areport for which the source is excel.When I publish the crystal report in infoview,it prompts for db login while refreshin the report.Even though I set theoption to use the same database login at CMC level,it did not work
I have created a DAO connection forexcel and then generated the report.
Kindly suggest a solution as it is not a problem only with excel source.
Reply | Email | Modify 
attaching subreports dynamically by Vishal On October 21, 2010
Is it possible to use some sort of a sub-report template which can be attached to the main report dynamically in a loop via code behind?
I have 4 very different data tables each for a certain key value and the number of key values can be several but these 4 data tables for a key value have to appear together one after the other as if 4 static sub reports were laid out, one each for each data table. the tricky part is the same thing has to be repeated for subsequent key values.
please let me know if you are able to read through my description or i need to provide an example.

thanks.
Reply | Email | Modify 
crystal report by arish On September 2, 2011
i want to disply the record from two different storeprocedure into one crystal report what can i do for that please tell me
Reply | Email | Modify 
Re: crystal report by Sarim On September 3, 2011
Crystal report can only bind with a single result set. you need to merge the result into one if you are not using subreport. In case of sub report you can do it.
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.