Displaying IEnumerable .NET Collection with Crystal Reports

February 26, 2008 at 11:41 AMAmer Gerzic

In my previous post Displaying .NET DataSet with Crystal Reports I discussed one way to report the data that does not come directly from a database. In this way, it is possible to preform more complex data analysis and present the result using Crystal Report engine. Following post addresses similar issue. However, here, the data to be presented is not stored in a DataSet, but rather in a .NET Collection, which implements IEnumerable interface.

To achieve required result, we'll first define a structure to be presented in the report. Actually, we are defining record structure with each public class member representing a column. For simplicity we are defining only single member of type string:

namespace CrystalReportApp
{
    public class Class1
    {
        public Class1(string s)
        {
            myString = s;
        } 

        public String myString;
    }
}

Once the record structure is defined (in this case Class1), we are ready to design the report:

  1. In solution explorer, right-click on your project and select Add - New Item
  2. From Add New Item dialog select Crystal Report
  3. A report will be added and report wizard will start. At this point make sure that as data source following is selected: Project Data - .NET Objects - CrystalReportApp.Class1
  4. Add myString to the list of fields to be displayed in the report.

At this point report design is completed. All it's left is to tie the report with the data, as well as generate some data to be displayed. Following code is performing all necessary steps:

CrystalReport2 Report = new CrystalReport2(); 

Class1[] array = new Class1[5]; 

array[0] = new Class1("Line 1");
array[1] = new Class1("Line 2");
array[2] = new Class1("Line 3");
array[3] = new Class1("Line 4");
array[4] = new Class1("Line 5"); 

Report.SetDataSource(array); 

crystalReportViewer1.ReportSource = Report;

At first we create report object then array of records (Class1 objects). We add some records to the array, and tie the array to the report (Report.SetDataSource(array)). Last line takes care of displaying the report in Crystal Reports viewer.

Posted in: .NET | ASP.NET | C# | Crystal Reports

Tags: , ,

Add comment

biuquote
Loading