Skip to main content
All docs
V23.2

Create a Table Report in Code

  • 3 minutes to read

The following code sample creates a new SqlDataSource, creates a report with the XRTable control at runtime, and binds the table to data:

Table Report in Code

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.ComponentModel.CancelEventArgs 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;
}

Examples

The following sample projects illustrate how to create a table report:

View Example: Reporting for WinForms - Create a Data-Bound Table at Runtime

Table Report

View Example: Reporting for Web Forms - How to Dynamically Generate a Report for a Table or Query

Table Report with Parametrized SQL Query