Bind a Report to a List Object at Design Time and Supply Data at Runtime
- 4 minutes to read
This tutorial uses an object data source to bind a report to a List<T> object.
Create a new application or open an existing application. For more information, review the following help topic: Get Started with DevExpress Reporting.
- Add a new blank report to it.
Add a new Data.cs file with the following code to the application:
Rebuild the solution.
Invoke the Data Source Wizard and follow the Wizard’s steps to bind the report to the Data object.
Drop data fields from the Field List onto the report.
Handle the Form1_Load event to populate and assign the report’s data source.
using System; using System.Collections.Generic; using DevExpress.XtraReports.UI; namespace ReportingListObjectSample { public partial class Form1 : DevExpress.XtraEditors.XtraForm { public Form1() { InitializeComponent(); this.Load += Form1_Load; } private void Form1_Load(object sender, EventArgs e) { XtraReport1 report = new XtraReport1(); var odses = DataSourceManager.GetDataSources<ObjectDataSource>(report); foreach (var ods in odses) { if(ods.DataSource is Type t && t == typeof(Data)){ ods.Constructor = null; ods.DataSource = CreateData(); } } ReportPrintTool tool = new ReportPrintTool(report); tool.ShowPreview(); } private List<Data> CreateData() { List<Data> data = new List<Data>(); Data item1 = new Data { Date = DateTime.Now, Id = 0, Name = "First" }; data.Add(item1); Data item2 = new Data { Date = DateTime.Now, Id = 1, Name = "Second" }; data.Add(item2); Data item3 = new Data { Date = DateTime.Now, Id = 2, Name = "Third" }; data.Add(item3); return data; } } }
Run the application and view the result.
Tips and Limitations
A direct assignment of the List<Data> property to the report’s DataSource property at runtime is not recommended because the List<Data> object may be disposed of at some stages of document generation, such as when report parameters are applied.
Use the ObjectDataSource class as the data source and the DataSourceManager class to assign a data source to your report at runtime. Once you bind a report to an object schema, you can access an instance of the ObjectDataSource class and assign the desired data model to that instance. The schema of the assigned model must be equal to the schema of the object to which the report was bound in the Designer.
Note that you can use a model data source object when developing an application, and at runtime replace the model object with a working object.