How to set datasource of Sub crystal report in c# win form app
Asked Answered
S

3

7

I am using this code to load a main report and a subreport inside the main report. The main report is a blank one and just contains subreport.

Here is my code:

MySqlConnection cnn;
string connectionString = null;
string sql = null;

connectionString = "Server = BC; Database = mydb1; Uid = root; Pwd = abc123;";
cnn = new MySqlConnection(connectionString);
cnn.Open();

sql = "SELECT * from mytable1 ";
MySqlDataAdapter dscmd = new MySqlDataAdapter(sql, cnn);
DataSet1 ds = new DataSet1();
dscmd.Fill(ds, "Imagetest");
cnn.Close();

ReportDocument cryRpt = new ReportDocument();
cryRpt.Load("C:/Subreport.rpt");
cryRpt.SetDataSource(ds.Tables[1]);

crystalReportViewer1.ReportSource = "C:/MainReport.rpt";
crystalReportViewer1.Refresh();

When I run the application I just see main report with blank subreport.

Sorel answered 4/11, 2011 at 7:48 Comment(0)
O
13
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load("C:/MainReport.rpt");
cryRpt.DataSourceConnections.Clear();
cryRpt.SetDataSource(ds.Tables[0]);
cryRpt.Subreports[0].DataSourceConnections.Clear();
cryRpt.Subreports[0].SetDataSource(ds.Tables[0]);
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
Ornithorhynchus answered 4/11, 2011 at 13:53 Comment(0)
L
0

Simply do this:

...
DataSet ds = new DataSet();
dscmd.Fill(ds, "DataTable1");
...

ReportDocument cryRpt = new ReportDocument();
cryRpt.Load("C:/MainReport.rpt");
cryRpt.SetDataSource(ds);

crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();

Note I'm creating a new DataSet and not a type derived from the DataSet.

In the report/subreport database fields menu, the table must have the same name as the DataTable:

Table in Database Fields menu must have the same name as the DataTable

And the Datasource location for reports and subreports must be the same: Datasource location for main report

Path for connection report and subreport are the same

This will bind the source tables by name with the .rpt file. Doing in this way you no longer need to set the data for each subreport by code.

Lotion answered 8/10, 2019 at 19:19 Comment(0)
B
-1

This helped me in a direction to understand that for a sub report to work, you still need to include the DataTbale on the main report.

Benzofuran answered 17/11, 2022 at 10:25 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.