Reporting - Combining ReportViewer and MS Charts

Introduction

There is often a requirement in business applications to display charts to analyze data and create reports to document and distribute results from an application. Microsoft has developed several tools to meet these needs. Visual Studio comes with a Report type and a ReportViewer control that takes advantage of Microsoft Reporting Services. Additionally, you can download an add-on for .NET 3.5 SP1 and Visual Studio 2008 to support robust charts without purchasing expensive, proprietary software. We will use Visual Studio 2008 and .NET 3.5 SP1 to demonstrate a simple application that will display a chart and allow the user to create a report that can be saved or printed with the chart information. The Reporting Services framework offers a chart element that you can add to your reports, but we will be using a chart from the Microsoft Chart Controls. We have found that the Microsoft Chart Controls offer a lot of flexibility and ease-of-use that is lost with the built-in report chart element. In addition, with our method, you can reuse the chart in several places in your application as well as the report, reducing rework when a change needs to be made to a chart. In order to follow along with the example in this article, you will need to install Microsoft Chart Controls for Microsoft .NET Framework 3.5 and Microsoft Chart Controls Add-on for Microsoft Visual Studio 2008. If you are new to MS Charts, you can check out this overview to help you get started and set up.

To get started, create a new Windows Forms project called "Report Project Demo." We will be using simple classes to be used as the data source for the chart and report. Add two new classes, ReportData and SalespersonData. In the SalespersonData class add the following code:

The basic foundation for the data we are going to use is now in place. Keep in mind that all .NET data sources are supported by MS Charts. This means you can use arrays, data views, data tables, XML, etc.

Drag the Chart control from the Data section of the Toolbox onto the design surface of Form1. Rename the chart to chartSales. It will already have a default data series named "Series1" that we will be using.

Add the following using statement to the Form1 code-behind:

using System.Windows.Forms.DataVisualization.Charting;

Since you have already placed the Chart control on the form, Visual Studio has added the DataVisualization reference to the project's References folder.

The next step is to wire up the chart to display the sales data we created as a simple bar graph. To do this, create the form's Load event and add the following code: