Sunday, September 20, 2009

How to Create a Crystal Report Sub Report in C#.NET

First you need to create the main report.  (Read .. How to Create a Crystal Report using Data sets in C#.NET)

Then right click the area which you want to insert a sub report. In my example I’m going to create a sub report for displaying InvoiceNumber , Balance (refer to my previous post) .

image

Then place the report and design the sub report as we did in the main report. Finally right click the sub report and go to Format Object and Give the Object name as SubBalance.  also give the report name as SubBalance when the time of creating the report. Now your main report looks like ..

image

Now you need to load data to the sub report as well as main report when we press the select button using data adapters. (refer Previous post )

private void btnView_Click(object sender, EventArgs e)
{
SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();
cb.UserID = "sa";
cb.Password = "sa123";
cb.InitialCatalog = "CustomerInfo";

// Create SQL Connection
SqlConnection sc = new SqlConnection(cb.ConnectionString);

CusDataSetTableAdapters.CusMainTableAdapter Ta =
new
CusDataSetTableAdapters.CusMainTableAdapter();
Ta.Connection = sc;
CusDataSet.CusMainDataTable Td = Ta.GetDataByName(txtCusName.Text);

// Create the mainReport
CustomerInfo Ci = new CustomerInfo();
Ci.SetDataSource((DataTable)Td);

// Load data to the sub report
CusDataSetTableAdapters.CusBalanceTableAdapter Tas =
new
CusDataSetTableAdapters.CusBalanceTableAdapter();
Tas.Connection = cn;
CusDataSet.CusBalanceDataTable dts =
Tas.GetBalanceByCusName(txtCusName.Text);
Ci.Subreports["SubBalance"].SetDataSource((DataTable)dts);

crystalReportViewer1.ReportSource = Ci;

}

(Read .. Hide and Show Crystal Report’s Sub Report when we need)

Post a Comment