[T]here are reasons why i write this crystal report tutorial using IEnumerable data source. First, using IEnumerable we can set data for the report without database in an easy way. Second, we can also using IEnumerable to work with data from database.
Aside from that, IEnumerable is widely used to store data as in Entity Framework or if you ever create repository using ADO.NET and write raw query there, you should get what i’m talking about.
Creating Report
We will need windows form application to make it working, before you go to next steps, create this type of project first.
If you have installed Crystal Report you will see on the Toolbox a CrystalReportViewer component under Reporting node. Drag and drop it into your form.
Your form now should looks like this
Model, we need a model to hold the value of something we need to display in the report. In this case i create Book model. For simplicity there are only 4 fields.
1 2 3 4 5 6 7 |
public class Book { public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } public string Publisher { get; set; } } |
Next add new item which is Crystal Report itself, name it BookReport
On the pop up dialog choose Using the Report Wizard and Standard
On next window select Project Data – .NET Objects – BookCrystalReport.Book (class model we created before) and mark it as selected tables.
Last, select all fields and click Finish.
Open your BookReport, it looks like this
Now it is time to fill the report with data. Again, for simplicity i use in memory data but if you know repository pattern that its return value is list of an object you will have no problem to use it with database.
On the code behind of the form modify the constructor as below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public Form1() { InitializeComponent(); var books = new List<Book>() { new Book(){Id=1,Title="Book One",Author="Author One",Publisher="Publisher One"}, new Book(){Id=2,Title="Book Two",Author="Author Two",Publisher="Publisher Two"}, new Book(){Id=3,Title="Book Three",Author="Author Three",Publisher="Publisher Three"}, new Book(){Id=4,Title="Book Four",Author="Author Four",Publisher="Publisher Four"}, new Book(){Id=5,Title="Book Five",Author="Author Five",Publisher="Publisher Five"} }; BookReport report = new BookReport(); report.SetDataSource(books); crystalReportViewer.ReportSource = report; } |
Run the program and if you have error like below image you only need a little modification.
Open your App.config and modify
1 |
<startup useLegacyV2RuntimeActivationPolicy="true"> |
Run the program again, this should be your prize