Manage Data Sources at Runtime
- 3 minutes to read
When you create a reporting application, you might need to modify or configure data sources for your reports at runtime. Such runtime configuration/modification can be required in the following cases:
- You want to add data sources to the End-User Report Designer, so that these data sources are displayed in the Field List and can be used in a report after the designer is invoked.
- You need to work with a data source schema only in the End-User Report Designer, and supply data to the data source when end users switch to a report preview.
- You wish to change a data source’s connection settings to switch from test data to production data in your application at runtime.
- Other situations in which configuration or modification is required at runtime.
The DataSourceManager Class Overview
The listed and other similar tasks can be solved with the use of the DataSourceManager class. This static class contains five methods that allow you to do basic operations with report data sources:
- GetDataSources
- Returns all report data sources.
- AddDataSources
- Adds the specified data sources to a report.
- ReplaceDataSource
- Replaces a report’s current data source with the specified data source.
- GetDataSourceAssignables
- Returns a report and its elements (subreports, controls, bands, parameters) to which a data source can be assigned.
- GetDataSourceAssignablesByDataSource
- Returns a report and its elements (subreports, controls, bands, parameters) to which the specified data source is assigned.
The sections below contain two examples on how to use the DataSourceManager class methods. For more information on typical tasks related to runtime configuration/modification of report data sources and an explanation on how to solve these tasks, refer to the description of the DataSourceManager class and its methods.
Add Data Sources to a Report
The following code sample adds two JSON data sources to a report:
using DevExpress.DataAccess.Json;
using DevExpress.XtraReports;
//...
var report = new XtraReport1();
var jsonDataSource1 = new JsonDataSource { /* ... */ };
var jsonDataSource2 = new JsonDataSource { /* ... */ };
DataSourceManager.AddDataSources(report, jsonDataSource1, jsonDataSource2);
Update Query Parameters of the SqlDataSource Component
The following code template shows how to use the GetDataSources method to retrieve all data sources of the SqlDataSource type and update their query parameters.
using DevExpress.DataAccess.Sql;
using DevExpress.XtraReports;
//...
var report = new XtraReport1();
var sqlDataSources = DataSourceManager.GetDataSources<SqlDataSource>(
report: report,
includeSubReports: true
);
foreach (var sqlDataSource in sqlDataSources) {
foreach (var query in sqlDataSource.Queries) {
query.Parameters["paramName"].Value = 32;
}
}