Introduction

RDLC is the acronym for Report Definition Language Client-side. RDLC is the default reporting tool for Visual Studio. In this tutorial, you are going to learn how to create professional looking reports in C#.

Topics to be covered

We will cover the following topics in this tutorial
  • Tutorial pre-requisites
  • RDLC Report Data Source
  • Adding a RDLC Report to your project
  • RDLC Report Sections
  • RDLC Report Built-in functions
  • RDLC Report Viewer
  • Report Viewer Data Source

Tutorial Pre-requisites

This tutorial assumes you are;
  • C# Programming basics
  • You have Visual Studio installed
  • SQL Server installed

RDLC Report Data Source

We will first need to create a new Visual Studio C# project. Create a new project in Visual Studio and name it RDLCReport. We will need to create a dataset that we will use when creating the RDLC Report using the wizard.
  1. Press Ctlr + Shift + A to add a new item
  2. From the Add New Item dialog window that appears, on the left hand side panel, click on Data
  3. Select DataSet
  4. Enter dsProducts.xsd as the DataSet name and click on add button.
  5. Open the toolbox and add a DataTable to the DataSet dsProducts.xsd
  6. Name the DataTable products
Products DataTable fields Add the following fields
  • id
  • product_name
  • price
  • quantity_on_hand
Your DataSet should now look as follows dataset Select price field Open the properties panel and set the DataType to System.Int32. Do the same for quantity_on_hand

Adding a RDLC Report to your project

We will now add a RDLC Report to our project using a wizard Press Ctrl + Shift + A on the keyword Select reporting on the left hand side panel Select Report Wizard Name the report rptProducts.rdlc Click on Add button You will get the following wizard rdlc_report_wizard Enter dsProducts as the Dataset name Choose dsProducts as the Data source Click on Next button rdlc_report_wizard_2 Drag the available fields and drop them on Values column as shown in the image above Click on Next button You will get the Choose the layout dialog page, click on Next button again You will get the Choose a style page, select Generic as shown in the image below rdlc_report_wizard_style Click on Finish button The report will open in Visual Studio.

RDLC Report Sections

By default, the header and footer are not displayed. Let’s start by displaying them. Right click on the report and select Page Header Right click on the report and select Page Footer You report should now appear as follows rdlc_report_sectionsHERE,
  1. Page Header – this section contains information such as the company name, logo, report title etc.
  2. Details section – this is where the data from the data source is displayed
  3. Report footer – anything placed in this section appears at the end of the rows that are displayed on the report. This section is useful for data such as total number of rows, grand totals etc.
  4. Page footer – this section usually contains information such as print date, total number of pages etc. It appears on every page.
Let’s now add a title to our report Open the toolbox Add a textbox to the header section Enter products listing as the report title

RDLC Report Built-in fields

RDLC Reports have a number of built-in fields such as Execution Time, Current Page Number, and Total Number of Pages etc. For now, we will add the Execution Time and Total page count to our report Drag and drop the Execution Time in the footer area Add a text box at the far right hand side of the footer and enter Page of as shown in the image below rdlc_report_footer We will now drag Page Number and Total Pages built-in fields into the text box with Page of. Your report footer should now appear as follows rdlc_report_footer_2

RDLC Report Viewer

Now that we have designed our report, its time to display it in a form Open Form1.cs Open the toolbox Add a report viewer to the form. The report viewer is the one that is responsible for loading the report Open the properties window and set the dock property to parent. This will make the report view fill up the entire form.

Report Viewer Data Source

It’s now time to write some code that will connect to the database and get the data for us. The following script created a table products and adds some dummy records IN SQL Server.
CREATE DATABASE RDLCReport
GO

USE RDLCReport
GO

CREATE TABLE [dbo].[products](
	[id] [nvarchar](5) NOT NULL,
	[product_name] [nvarchar](50) NULL,
	[price] [numeric](18, 0) NULL,
	[quantity_on_hand] [numeric](18, 0) NULL,
 CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

INSERT INTO products (id,product_name,price,quantity_on_hand) 
VALUES ('ck','Coca Cola',600,67)
,('vk','Absolute Vodka',3200,5)
,('ap','Apple Juice',1130,15)
GO
  Double click on Form1.cs to enter the code window Modify the code to the following
using Microsoft.Reporting.WinForms;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace RDLCReport
{
    public partial class Form1 : Form
    {
        public static SqlConnection CN = new SqlConnection();
        string connection_string = "Data Source=127.0.0.1;Initial Catalog=RDLCReport;User ID=kr;Pwd=aise;TimeOut=0;";
        string sql_stmt = "SELECT * FROM products;";

        public static DataTable MyTable(string strSQL)
        {
            SqlDataAdapter dat = new SqlDataAdapter(strSQL, CN);
            DataTable tb = new DataTable();

            dat.Fill(tb);

            return tb;
        }

        public static ReportDataSource ReportDataSource(string dsDataSetName, string sqlStr)
        {
            ReportDataSource rs = new ReportDataSource(dsDataSetName, MyTable(sqlStr));
            return rs;
        }

        private void DBConnect()
        {
            try
            {
                CN.ConnectionString = connection_string;
                CN.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "DB Connection Error");
            }
        }

        private void LoadProductsReport()
        {
            reportViewer1.LocalReport.ReportEmbeddedResource = "RDLCReport.rptProducts.rdlc";

            reportViewer1.LocalReport.DataSources.Clear();

            reportViewer1.LocalReport.DataSources.Add(ReportDataSource("dsProducts", sql_stmt));
        }


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DBConnect();

            LoadProductsReport();

            reportViewer1.SetDisplayMode(DisplayMode.PrintLayout);

            reportViewer1.ZoomMode = ZoomMode.Percent;

            this.reportViewer1.RefreshReport();
        }
    }
}
HERE,
  • public static SqlConnection CN = new SqlConnection();  defines a database connection object
  • string connection_string…  defines a connection string and provides static values for connecting to the database. You should modify the connection string to match the settings on you SQL Server instance
  • string sql_stmt = "SELECT * FROM products;";  defines a string variable with a SELECT statement that retrieves all the products from the database
  • public static DataTable MyTable(string strSQL){…}  defines a function that accepts a SELECT SQL Statement and returns a data table
  • public static ReportDataSource ReportDataSource(string dsDataSetName, string sqlStr){…}  defines a function that returns a RDLC Report data source
  • private void DBConnect(){…}  defines a function that connects to the database
  • private void LoadProductsReport(){…}  defines the function that embeds our report to the report viewer, clears the existing data source and adds a new data source based on the data that we retrieve using the SELECT statement
  • SetDisplayMode(DisplayMode.PrintLayout);  sets the display mode of the RDLC report to print preview.
  • ZoomMode = ZoomMode.Percent;  sets the RDLC report zoom mode to 100 percent.
Press F5 on the keyboard to run the program You will get the following report rdlc_report

What’s next?

The next tutorial will show you how to pass parameters to a RDLC reports and format the report to make it more presentable.

Summary

In this tutorial, we have learnt how to create skinny models and take advantage of conventions over configurations. We also added common fields to our database for auditing purposes that the base model is taking care of.