Thursday, March 11, 2010

Crystal Report Binding using C#

For Crystal Report binding we can use this below code.

Parameters to be Passed
1. dsGlobal - Containing the Data for the Main and SubReport.
(We need to pass a Dummy Datatable if we dont have Databinding in Main Report apart from MainReport)
2. SFormName - The Crystal Report Name
3. sNamespace - To get the Full Path of the Crystal Report from a Project. If not remove this and give the full path in sFormName

This will create a temporary report and bind it with the Crystal report viewer.


private void ViewReport(DataSet dsGlobal, string sFormName, string sNamespace)
{
CrystalDecisions.Windows.Forms.CrystalReportViewer lobjReportViewer;
try
{
CrystalDecisions.Shared.DiskFileDestinationOptions lobjDFDO = new CrystalDecisions.Shared.DiskFileDestinationOptions();
CrystalDecisions.Shared.ExportOptions lobjOptions = new CrystalDecisions.Shared.ExportOptions();
ReportDocument lobjReport = new ReportDocument();

Assembly objAssembly = AppDomain.CurrentDomain.Load(sNamespace); ;
object objForm = null;
foreach (Type t in objAssembly.GetTypes())
{
if (t.Name.ToUpper() == sFormName.ToUpper())
{
objForm = Activator.CreateInstance(t);
break;
}
}
ReportDocument lobjDriverReport = (ReportDocument)objForm;
lobjReportViewer = new CrystalReportViewer();

if (lobjDriverReport.Subreports.Count > 0)
{
foreach (ReportDocument subrep in lobjDriverReport.Subreports)
{
if (dsGlobal.Tables[subrep.Name] != null)
{
lobjReport = lobjDriverReport.OpenSubreport(subrep.Name);
lobjReport.Database.Tables[0].SetDataSource(dsGlobal.Tables[subrep.Name]);
}
}
}

if (dsGlobal != null && dsGlobal.Tables.Count > 0 && dsGlobal.Tables[0] != null && dsGlobal.Tables.Count > 0 && dsGlobal.Tables[0].Rows.Count > 0)
{
lobjDriverReport.SetDataSource(dsGlobal.Tables[0]);
}

lobjDFDO.DiskFileName = System.Environment.CurrentDirectory + "\\" + System.DateTime.Now.ToLongDateString() + "Report.rpt";

lobjOptions.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile;
lobjOptions.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.CrystalReport;
lobjOptions.ExportDestinationOptions = lobjDFDO;
lobjDriverReport.Export(lobjOptions);

lobjReport = new ReportDocument();
lobjReport.Load(System.Environment.CurrentDirectory + "\\" + System.DateTime.Now.ToLongDateString() + "Report.rpt");

rptStorage.ReportSource = lobjReport;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

No comments:

Post a Comment