How to: Assign a DataSet to a Crystal report document
In my current project we use type DataSets as a source for the reports we build using Crystal Reports for VS.Net. How this works can be found in the Crystal Reports knowledge base, and more specific in this document.
One of the challenges there was to assign DataSets to the reports once it was created. Based on documentation from Business Objects, the following generic code assigns a DataSet to the ReportDocument and it's subreports.
void AssignDataSet(ReportDocument oReport, DataSet dsData)
{ DataSet dsNew = dsData.Copy();
// Remove primary key info. CR9 does not appreciate this information!!!
foreach (DataTable dataTable in dsNew.Tables)
{ foreach (DataColumn dataCol in dataTable.PrimaryKey)
{ dataCol.AutoIncrement = false;
}
dataTable.PrimaryKey = null;
}
// Now assign the dataset to all tables in the main report
foreach (CrystalDecisions.CrystalReports.Engine.Table oTable in oReport.Database.Tables)
{ oTable.SetDataSource(dsNew);
}
// Now loop through all the sections and its objects to do the same for the subreports
foreach (CrystalDecisions.CrystalReports.Engine.Section crSection in oReport.ReportDefinition.Sections)
{ // In each section we need to loop through all the reporting objects
foreach (CrystalDecisions.CrystalReports.Engine.ReportObject crObject in crSection.ReportObjects)
{ if (crObject.Kind == ReportObjectKind.SubreportObject)
{ SubreportObject crSubReport = (SubreportObject)crObject;
ReportDocument crSubDoc = crSubReport.OpenSubreport(crSubReport.SubreportName);
foreach (CrystalDecisions.CrystalReports.Engine.Table oTable in crSubDoc.Database.Tables)
{ oTable.SetDataSource(dsNew);
}
}
}
}
}