Create Reports in Code
- 11 minutes to read
The following steps describe how to create a report in code:
- Create an instance of the XtraReport class or implement an XtraReport class descendant.
- Assign a data source to the report: specify the DataSource and DataMember properties.
- Create bands and add them to the report’s Bands collection (the DetailBand is mandatory).
- Create report controls and add them to the report’s bands.
- Create styles for report elements.
Code Samples
The following code samples illustrate how to generate reports in code:
- Create a Simple Static Report
- Create a Simple Data-Bound Report
- Create a Simple Report with a Data-Bound Table
- Create a Master-Detail Report
- Create a Cross-Tab Report
- Create a Report with a Subreport
- Create a Table Report with Dynamic Columns
The following topics describe the report object model and events:
Create a Simple Static Report
The code sample below creates a new report, sets its name, display name, paper kind and margins, and adds the Detail Band band with the XRLabel control on it.
using System.Drawing;
using System.Drawing.Printing;
using DevExpress.XtraReports.UI;
// ...
public static XtraReport CreateReport() {
XtraReport report = new XtraReport() {
Name = "SimpleStaticReport",
DisplayName = "Simple Static Report",
PaperKind = PaperKind.Letter,
Margins = new Margins(100, 100, 100, 100)
};
DetailBand detailBand = new DetailBand() {
HeightF = 25
};
report.Bands.Add(detailBand);
XRLabel helloWordLabel = new XRLabel() {
Text = "Hello, World!",
Font = new Font("Tahoma", 20f, FontStyle.Bold),
BoundsF = new RectangleF(0, 0, 250, 50),
};
detailBand.Controls.Add(helloWordLabel);
return report;
}
Create a Simple Data-Bound Report
The following code sample creates a new object data source, creates a report with the XRLabel control at runtime, and binds the label to data.
For information on supported data sources, review the following article: Bind Reports to Data.
using System.Collections.Generic;
using System.Drawing;
using DevExpress.XtraPrinting;
using DevExpress.XtraReports.UI;
// ...
public class ReportCreator {
class Employee {
public string Name { get; set; }
}
public static XtraReport CreateReport() {
XtraReport report = new XtraReport() {
DataSource = CreateDataSource(),
StyleSheet = {
new XRControlStyle() { Name = "Title", Font = new Font("Tahoma", 20f, FontStyle.Bold) },
new XRControlStyle() { Name = "Normal", Font = new Font("Tahoma", 10f), Padding = new PaddingInfo(2, 2, 0, 0) },
}
};
var reportHeaderBand = CreateReportHeader("List of employees");
var detailBand = CreateDetail("[Name]");
report.Bands.AddRange(new Band[] { reportHeaderBand, detailBand });
return report;
}
static List<Employee> CreateDataSource() {
return new List<Employee>() {
new Employee() { Name = "Nancy Davolio" },
new Employee() { Name = "Andrew Fuller" },
new Employee() { Name = "Janet Leverling" },
new Employee() { Name = "Margaret Peacock" },
new Employee() { Name = "Steven Buchanan" },
new Employee() { Name = "Michael Suyama" },
new Employee() { Name = "Robert King" },
new Employee() { Name = "Laura Callahan" },
new Employee() { Name = "Anne Dodsworth" }
};
}
static ReportHeaderBand CreateReportHeader(string title) {
ReportHeaderBand reportHeaderBand = new ReportHeaderBand() {
HeightF = 50
};
XRLabel titleLabel = new XRLabel() {
Text = title,
BoundsF = new RectangleF(0, 0, 300, 30),
StyleName = "Title"
};
reportHeaderBand.Controls.Add(titleLabel);
return reportHeaderBand;
}
static DetailBand CreateDetail(string expression) {
DetailBand detailBand = new DetailBand() {
HeightF = 25
};
XRLabel detailLabel = new XRLabel() {
ExpressionBindings = { new ExpressionBinding("Text", expression) },
BoundsF = new RectangleF(0, 0, 300, 20),
StyleName = "Normal"
};
detailBand.Controls.Add(detailLabel);
return detailBand;
}
}
Create a Simple Report with a Data-Bound Table
The following code sample creates a new SqlDataSource, creates a report with the XRTable control at runtime, and binds the table to data:
using DevExpress.DataAccess.ConnectionParameters;
using DevExpress.DataAccess.Sql;
using DevExpress.XtraReports.UI;
// ...
private static XtraReport CreateReport()
{
// Creates a new data source.
SqlDataSource sqlDataSource = CreateSQLDataSource();
// Creates a new report and assigns the data source.
XtraReport report = new XtraReport();
report.DataSource = sqlDataSource;
report.DataMember = "selectQuery";
// Creates a detail band and adds it to the report.
DetailBand detailBand = new DetailBand();
report.Bands.Add(detailBand);
// Creates a table and adds it to the detail band.
XRTable table = new XRTable();
detailBand.Controls.Add(table);
// Creates a row and adds the product name and product price cells to the row.
table.BeginInit();
XRTableRow row = new XRTableRow();
table.Rows.Add(row);
XRTableCell productName = new XRTableCell();
XRTableCell productPrice = new XRTableCell();
row.Cells.Add(productName);
row.Cells.Add(productPrice);
// Binds the table cells to the data fields.
productName.ExpressionBindings.Add(new ExpressionBinding("BeforePrint", "Text", "[ProductName]"));
productPrice.ExpressionBindings.Add(new ExpressionBinding("BeforePrint", "Text", "[UnitPrice]"));
// Adjust the table width.
table.BeforePrint += Table_BeforePrint;
table.EndInit();
return report;
}
private static void Table_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
XtraReport report = (sender as XRTable).RootReport;
(sender as XRTable).WidthF = report.PageWidth - report.Margins.Left - report.Margins.Right;
}
private static SqlDataSource CreateSQLDataSource()
{
// Creates a data source.
SQLiteConnectionParameters connectionParameters = new SQLiteConnectionParameters("Data/nwind.db", "");
SqlDataSource dataSource = new SqlDataSource(connectionParameters);
// Creates a SELECT query.
SelectQuery query = SelectQueryFluentBuilder
.AddTable("Products")
.SelectColumn("ProductName")
.SelectColumn("UnitPrice")
.Build("selectQuery");
// Adds the query to the collection and returns the data source.
dataSource.Queries.Add(query);
dataSource.Fill();
return dataSource;
}
Create a Cross-Tab Report
The following code sample creates a new SqlDataSource, creates a report with the XRCrossTab control at runtime, and binds the Cross Tab control to data:
using DevExpress.DataAccess.ConnectionParameters;
using DevExpress.DataAccess.Sql;
using DevExpress.XtraPrinting;
using DevExpress.XtraReports.UI;
using DevExpress.XtraReports.UI.CrossTab;
using System;
using System.Drawing;
using System.Windows.Forms;
// ...
private XtraReport CreateReport() {
// Creates a blank report.
XtraReport crossTabReport = new XtraReport() {
VerticalContentSplitting = VerticalContentSplitting.Smart,
HorizontalContentSplitting = HorizontalContentSplitting.Smart
};
// Creates a detail band and adds it to the report.
DetailBand detail = new DetailBand();
crossTabReport.Bands.Add(detail);
// Creates a cross tab and adds it to the Detail band.
XRCrossTab crossTab = new XRCrossTab();
detail.Controls.Add(crossTab);
crossTab.PrintOptions.RepeatColumnHeaders = true;
crossTab.PrintOptions.RepeatRowHeaders = true;
// Creates a data source.
SQLiteConnectionParameters connectionParameters = new SQLiteConnectionParameters(@"|DataDirectory|\nwind.db", "");
SqlDataSource ds = new SqlDataSource(connectionParameters);
// Creates an SQL query to access the SalesPerson view.
SelectQuery query = SelectQueryFluentBuilder.AddTable("SalesPerson")
.SelectColumn("CategoryName")
.SelectColumn("ProductName")
.SelectColumn("Country")
.SelectColumn("FullName")
.SelectColumn("Quantity")
.SelectColumn("ExtendedPrice").Build("SalesPerson");
ds.Queries.Add(query);
// Binds the cross tab to data.
crossTab.DataSource = ds;
crossTab.DataMember = "SalesPerson";
// Generates cross tab fields.
crossTab.RowFields.Add(new CrossTabRowField() { FieldName = "CategoryName" });
crossTab.RowFields.Add(new CrossTabRowField() { FieldName = "ProductName" });
crossTab.ColumnFields.Add(new CrossTabColumnField() { FieldName = "Country" });
crossTab.ColumnFields.Add(new CrossTabColumnField() { FieldName = "FullName" });
crossTab.DataFields.Add(new CrossTabDataField() { FieldName = "Quantity" });
crossTab.DataFields.Add(new CrossTabDataField() { FieldName = "ExtendedPrice" });
crossTab.GenerateLayout();
// ...
// Adjusts the generated cells.
foreach(var c in crossTab.ColumnDefinitions) {
// Enables auto-width for all columns.
c.AutoWidthMode = DevExpress.XtraReports.UI.AutoSizeMode.GrowOnly;
}
foreach(XRCrossTabCell c in crossTab.Cells) {
if(c.DataLevel == 1 && c.RowIndex != 2) {
// Adjusts format string for the "Extended Price" cells.
c.TextFormatString = "{0:c}";
}
}
// Assigns styles to the cross tab.
crossTab.CrossTabStyles.GeneralStyle = new XRControlStyle() {
Name = "Default",
Borders = BorderSide.All,
Padding = new PaddingInfo() { All = 2 }
};
crossTab.CrossTabStyles.DataAreaStyle = crossTab.CrossTabStyles.TotalAreaStyle = new XRControlStyle() {
Name = "Data",
TextAlignment = TextAlignment.TopRight
};
crossTab.CrossTabStyles.HeaderAreaStyle = new XRControlStyle() {
Name = "HeaderAndTotals",
BackColor = Color.WhiteSmoke
};
return crossTabReport;
}
Troubleshooting
If a runtime-generated report does not work as expected or you want to know how to implement a particular feature in code, follow these steps:
- Use the report’s SaveLayoutToXml method to save the generated report as a REPX file.
Add a new report to your .NET Framework project, expand the report’s smart tag, and import the generated REPX file.
Specify the report’s data source and preview the changes.
- Modify the report layout.
- The
XtraReport.Designer.cs
orXtraReport.Designer.vb
file contains code that generates the report. Use this code in your application to get a similar result.