How to create an RDL report in code

While RDL reports are easy enough to create in a designer, you may need to conditionally manage data-binding of a page or report at run time. Or you might need to make a minor change to the layout of a report based on some user input. In short, you need to create an RDL report in code. This blog walks you through that process, and you can also download the sample code to use in your report app.

Download the sample

In this blog, we'll go over:

Setting up the project

I want to create a project that shows me a list of countries on the left side of the page. If I select a country, I'll see a report displaying all of my customers that reside in the country, along with their contact information. Something like this:

First, create a new Empty Web Application:

Next, add a new Web Form to our project, titled MainPage.aspx:

To display our list of countries we'll use the ASP.NET ListBox control:

<form id="form1" runat="server"> 

<div class="inlineBlock">
            <asp:listbox id="ListBox1" runat="server" height="775px" width="200" autopostback="True" onselectedindexchanged="ListBox1_SelectedIndexChanged"></asp:listbox>
        </div>

        <style type="text/css">.inlineBlock { display: inline-block; }</style> 
    </form>

In the Page_Load event, we’ll create a DataTable object and fill it with a list of countries from the Customers table in the NorthWind database:

protected void Page_Load(object sender, EventArgs e)
{
DataTable dtTable = new DataTable();
       try
       {
           string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=C:\\Users\\mateenf\\Documents\\GrapeCity Samples\\ActiveReports 11\\Data\\Nwind.mdb";
              string countries = "SELECT Distinct Country From Customers";
              OleDbConnection conn = new OleDbConnection(connStr);
              OleDbCommand cmd = new OleDbCommand(countries, conn);
              OleDbDataAdapter adapter = new OleDbDataAdapter();
              adapter.SelectCommand = cmd;
              adapter.Fill(dtTable);
}
       catch (Exception er)
       {
           Console.WriteLine(er.ToString());
       }
       if (!IsPostBack)
       {
            ListBox1.DataSource = dtTable;
              ListBox1.DataTextField = "Country";
              ListBox1.DataBind();
       }
}

We’re going to use the ListBox’s SelectedIndexChanged event to load the report.

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
     countriesList = ListBox1.SelectedValue;
       ViewReport();
}

Creating an RDL Report

For the RDL report, we'll need to create an instance of the report in the ViewReport() method:

PageReport rdlReport = new PageReport();
GrapeCity.ActiveReports.Document.PageDocument rdlDocument = new GrapeCity.ActiveReports.Document.PageDocument(rdlReport);

We also need to set the layout of the report:

rdlReport.Report.PaperOrientation = GrapeCity.ActiveReports.PageReportModel.PaperOrientation.Landscape;
rdlReport.Report.PageHeight = "8in";
rdlReport.Report.PageWidth = "11in";

And finally, the page header and page footer:

//Page Header
GrapeCity.ActiveReports.PageReportModel.PageHeaderFooter headers = new GrapeCity.ActiveReports.PageReportModel.PageHeaderFooter();
rdlReport.Report.PageHeader = headers;
headers.Height = ".5in";
headers.PrintOnFirstPage = true;
headers.PrintOnLastPage = true;

//Page Footer
GrapeCity.ActiveReports.PageReportModel.PageHeaderFooter footer = new GrapeCity.ActiveReports.PageReportModel.PageHeaderFooter();
rdlReport.Report.PageFooter = footer;
footer.Height = ".5in";
footer.PrintOnFirstPage = true;
footer.PrintOnLastPage = true;

Let's add a report title at the very top of the page:

GrapeCity.ActiveReports.PageReportModel.TextBox reportTitle = new GrapeCity.ActiveReports.PageReportModel.TextBox()
            {
                Name = "Report Title",
                Value = "List of Customers in: " + countriesList,
                Height = "0.5in",
                Width = "5in",
                Top = "0in",
                Left = "0.5in",
                Style = { TextAlign = "Left", FontSize = "18pt", FontWeight = "Bold" }
            };

We'll need to add every control in the report to the report definition. In this case, we need to add the “reportTitle” textbox:

rdlReport.Report.Body.ReportItems.Add(reportTitle);

Creating a Table in Code

Now the table displays our list of customers and their contacts in the specified country. So let’s create an instance of a Table object:

GrapeCity.ActiveReports.PageReportModel.Table customersTable = new GrapeCity.ActiveReports.PageReportModel.Table()
{
                Name = "CustomersTable",
                Top = "0.75in",
                Left = "0.5in",
                DataSetName = "MyDataSet"
};

The table needs five columns: Company Name, Contact Name, Address, City, and Phone. For each column, we need a table header, detail row, and table footer.

For the table headers, first we'll create the customerHeader cell that represents a cell in the table header:

//Creating table header
customersTable.Header = new GrapeCity.ActiveReports.PageReportModel.Header();
customersTable.Header.TableRows.Add(new GrapeCity.ActiveReports.PageReportModel.TableRow() { Height = ".25in" });
var customerHeader = customersTable.Header.TableRows[0].TableCells;

We then format the customerHeader cell for each of the five columns and add it to the table:

//First cell in the table header
customerHeader.Add(new GrapeCity.ActiveReports.PageReportModel.TableCell());
customerHeader[0].ReportItems.Add(new GrapeCity.ActiveReports.PageReportModel.TextBox()
{
                Name = "Company Name",
                Value = "Company Name",
                Style = { BorderStyle = { Top = "Solid", Bottom = "Solid", Left = "Solid" },
                    VerticalAlign = "Middle",
                    TextAlign = "Center",
                    BackgroundColor = "PowderBlue",
                    FontWeight = "Bold" }
            });
customersTable.TableColumns.Add(new GrapeCity.ActiveReports.PageReportModel.TableColumn() { Width = "2in" });

//Second cell in the table header
customerHeader.Add(new GrapeCity.ActiveReports.PageReportModel.TableCell());
customerHeader[1].ReportItems.Add(new GrapeCity.ActiveReports.PageReportModel.TextBox()
{
                Name = "Contact Name",
                Value = "Contact Name",
                Style = { BorderStyle = { Top = "Solid", Bottom = "Solid" },
                    VerticalAlign = "Middle",
                    TextAlign = "Center",
                    BackgroundColor = "PowderBlue",
                    FontWeight = "Bold" }
});
customersTable.TableColumns.Add(new GrapeCity.ActiveReports.PageReportModel.TableColumn() { Width = "2in" }); 

We repeat this formatting for the rest of the three columns while changing the Name and Value properties accordingly.

Next, we add a Details row to the table. We only need to create one details row that repeats as many times as there are records. Creating a details row follows the same procedure as creating the header row: first, we create the customerDetails cell that represents a cell in the table details row:

//Detail Row
customersTable.Details.TableRows.Clear();
customersTable.Details.TableRows.Add(new GrapeCity.ActiveReports.PageReportModel.TableRow() { Height = ".4in" });
var customerDetails = customersTable.Details.TableRows[0].TableCells;

We then format the customerDetails cell for each column and add it into the details row:

//First cell in the Details row
customerDetails.Add(new GrapeCity.ActiveReports.PageReportModel.TableCell());
customerDetails[0].ReportItems.Add(new GrapeCity.ActiveReports.PageReportModel.TextBox()
{
                Name = "CompanyNameBox",
                Value = "=Fields!CompanyName.Value",
                Width ="2in",
                Style = { TextAlign = "Center" }
});

//Second cell in the Details row
customerDetails.Add(new GrapeCity.ActiveReports.PageReportModel.TableCell());
customerDetails[1].ReportItems.Add(new GrapeCity.ActiveReports.PageReportModel.TextBox()
{
                Name = "ContactNameBox",
                Value = "=Fields!ContactName.Value",
                Width ="2in",
                Style = { TextAlign = "Center" }
});

Next, repeat the formatting for each of the remaining three columns, changing the Name and Value properties accordingly.

After having created the table footer in a similar way, add the customersTable to the report definition:

rdlReport.Report.Body.ReportItems.Add(customersTable);

Databinding

To manage the databinding, we’re going to add a Datasource and a Dataset to the report definition in the ViewReport() method:

rdlReport.Report.DataSources.Add(myDataSource());
rdlReport.Report.DataSets.Add(myDataSet());

We use the myDataSource() method to create a datasource connection:

private GrapeCity.ActiveReports.PageReportModel.DataSource myDataSource()
{
            GrapeCity.ActiveReports.PageReportModel.DataSource myDS = new GrapeCity.ActiveReports.PageReportModel.DataSource();
            myDS.Name = "MyDataSource";
            myDS.ConnectionProperties.DataProvider = "SQL";
            myDS.ConnectionProperties.ConnectString = "initial catalog=NWind;integrated security=SSPI;data source=localhost;persist security info=False;";
            return myDS;
}

In the myDataSet(), we retrieve the data and manually add fields to the dataset:

private GrapeCity.ActiveReports.PageReportModel.IDataSet myDataSet()
{
            GrapeCity.ActiveReports.PageReportModel.DataSet myDSet = new GrapeCity.ActiveReports.PageReportModel.DataSet();
            GrapeCity.ActiveReports.PageReportModel.Query myQuery = new GrapeCity.ActiveReports.PageReportModel.Query();
            myDSet.Name = "MyDataSet";
            myQuery.DataSourceName = "MyDataSource";
            myQuery.CommandText = "SELECT * From Customers where Country = '" + ListBox1.SelectedValue + "'";
            myDSet.Query = myQuery;

            //Create individual fields
            GrapeCity.ActiveReports.PageReportModel.Field country = new GrapeCity.ActiveReports.PageReportModel.Field("Country", "Country", null);
            GrapeCity.ActiveReports.PageReportModel.Field compName = new GrapeCity.ActiveReports.PageReportModel.Field("CompanyName", "CompanyName", null);
            GrapeCity.ActiveReports.PageReportModel.Field contactName = new GrapeCity.ActiveReports.PageReportModel.Field("ContactName", "ContactName", null);
            GrapeCity.ActiveReports.PageReportModel.Field address = new GrapeCity.ActiveReports.PageReportModel.Field("Address", "Address", null);
            GrapeCity.ActiveReports.PageReportModel.Field cityName = new GrapeCity.ActiveReports.PageReportModel.Field("City", "City", null);
            GrapeCity.ActiveReports.PageReportModel.Field phone = new GrapeCity.ActiveReports.PageReportModel.Field("Phone", "Phone", null);

            //Add fields to the dataset
            myDSet.Fields.Add(country);
            myDSet.Fields.Add(compName);
            myDSet.Fields.Add(contactName);
            myDSet.Fields.Add(address);
            myDSet.Fields.Add(cityName);
            myDSet.Fields.Add(phone);

            return myDSet;
}

Note that we're passing a parameter in the query to filter the data based on the selected country from the ListBox.

Viewing the report in the ASP.NET Viewer

From the Visual Studio Toolbox, drop the ActiveReports 12 WebViewer control to the body of the MainPage.aspx:

Going back to the end of the ViewReport() method, add a line to run the report:

  rdlReport.Run();

The ASP.NET viewer has two modes in which to render the report: Paginated and Galley. Paginated, as it sounds, breaks up the report into multiple pages based on the page size we specified in the ViewReport() method.

Galley mode, on the other hand, displays the entirety of the report in single, scrollable, view. The report we’ve created is a bit too large for paginated view, so we'll use Galley mode:

  WebViewer1.RenderMode =  GrapeCity.ActiveReports.Web.RenderMode.Galley;

Lastly, we pass the report to the viewer to display:

  WebViewer1.Report =  rdlReport;

And we should get our desired outcome:

Get the sample code

Download ActiveReports 12

Mateen Firoz

Product Manager
comments powered by Disqus