To read the article online, visit

Using Microsoft's Chart Controls In An ASP.NET Application: Programmatically Generating Chart Images

By Scott Mitchell


The Microsoft Chart controls demos we have examined so far all use the Chart Web control to position the chart image on the web page and to configure a number of its stylistic settings. For example, while the Plotting Chart Data article showed several demos illustrating the different ways to specify the points to plot on the chart surface, all of these demos used a Chart Web control to indicate where on the page the chart should appear, along with its dimensions, its series, its chart areas, its colors, and so on. While the Chart Web control makes it easy to get started with the chart, it is not necessary. From the ASP.NET page's code-behind class you can: programmatically create a Chart object; specify its width, height, colors, and other display-related properties; plot the charts data points through any of the mechanisms discussed in Plotting Chart Data; and generate an image for the chart in a number of different image formats, saving the image data to a file or to a stream.

Being able to programmatically configure the chart and generate the chart image is useful if you want to modify the chart image in some way before displaying it. Perhaps you want to add a watermark, or embed it inside a PDF file. Maybe you don't want to display it at all, but instead want to send it as an attachment in an email, or save the image to the web server's file system or to the database. Whatever the scenario, the good news is that the Microsoft Chart controls make it easy to programmatically create, customize, and generate the chart image.

This article looks at how to programmatically create a chart. Specifically, we'll see how to dynamically add a watermark to the generated chart image, as well as how to email the chart to a recipient. The demos in this installment do not use the Chart Web control at all; instead, the charts in these demos are created and rendered directly from the ASP.NET pages' code-behind classes. Read on to learn more!

Programmatically Creating The Chart And Plotting Its Data Points

All of the previous demos in this article series have used the Chart Web control when working with the Microsoft Chart controls. The Chart Web control renders an image element (<img>) that either references a static image file or an HTTP Handler, ChartImg.axd, depending on how you have configured the Chart control. (See Rendering the Chart for more information on how the Chart control renders the chart image.) In either case, our job as the developer is simple. All we need to do is set a few properties of the Chart control - the Width, Height, the series information, and so on - and then plot the data points. Behind the scenes, the Chart control generates the chart image.

The Chart Web control is a great time saver and should certainly be utilized when you are displaying a chart in a web page and are using the Web Forms programming model. However, if you are using ASP.NET MVC (which doesn't support Web controls), or need to generate the chart image but do not want to display it, or need to generate the chart image but modify it in some way before displaying it, then you will need to programmatically create the Chart object and write code to generate the chart image.

Let's look at how to accomplish this. To start, make sure that your ASP.NET page code-behind class (or wherever you're putting the chart generation code) imports the System.Web.UI.DataVisualization.Charting namespace, which is where the plethora of classes that makeup the Microsoft Chart controls reside. Next, create an instance of the Chart object. You can set its properties at this time, as well. The following snippet creates a new Chart object (salesChart) and sets its dimensions to 500x400.

'Create the Chart object and set some of its properties
Dim salesChart As New Chart
salesChart.Width = 500
salesChart.Height = 400

Next, plot the points. There are a variety of ways to do this programmatically, as covered in the Plotting Chart Data installment. If you are going to be frequently creating charts through programmatic means, I recommend that you familiarize yourself with K. Scott Allen's ChartBuilder class, which provides a simple API for plotting the points in a Chart object. (Scott introduced his ChartBuilder class in Charting With ASP.NET And LINQ.)

The following four lines of code uses Scott's ChartBuilder class to create a Sales By Category chart. All of the heavy lifting is handled by the SalesByCategoryChartBuilder class, which we examined in a demo in Plotting Chart Data. (The SalesByCategoryChartBuilder class extends Scott's ChartBuilder class.) In a nutshell, the SalesByCategoryChartBuilder class takes two inputs - the category name and order year - and plots the gross sales for the specified year for all products in the specified category.

Dim builder = New SalesByCategoryChartBuilder(salesChart)
builder.CategoryName = "Beverages"
builder.OrderYear = 1997

After the BuildChart method has completed, the Chart object contains information about its chart areas, series, and, most importantly, its data points, which are the sales figures for each of the products in the specified category. We are now ready to generate the chart image! The Chart object has a SaveImage method that can save the chart image to a file or a stream. To save it to a file, use:

salesChart.SaveImage(filePath, format)

To save the image to a location within your web application, use Server.MapPath. For example, to save the image to the Images folder in your application you could use the following code:

salesChart.SaveImage(Server.MapPath("~/Images/MyChart.png"), ChartImageFormat.Png)

Alternatively, you can save the image to a stream. The following snippet shows how to save the image as a PNG image to a MemoryStream object.

Using imgStream As New MemoryStream()
   salesChart.SaveImage(imgStream, ChartImageFormat.Png)

   ... Work with stream data ...
End Using

And that's how you programmatically create, customize, and generate a chart image. To hammer home these concepts, let's look at a couple of real world examples.

Adding A Watermark To Chart Images

If you want to modify the chart image before displaying it - say, by adding a watermark - you have two options:
  1. Use the Chart Web control and create an event handler for the Chart's PostPaint event. The PostPaint event fires after the chart image has been created and provides an opportunity for modifying the image before it is displayed.
  2. Programmatically create the chart image, modify it, and then display it.
Keep in mind that the Chart Web control handles generating the HTML to display the image, namely an <img> element. Moreover, it creates the static image file to display or references an HTTP Handler, ChartImg.axd, that does so. In either case, the chart image is not part of the ASP.NET page; rather, the chart image is either a file on disk or is generated on the fly by the HTTP Handler. The browser is making a separate HTTP request to get the chart image.

Consequently, if we decide to render the chart image programmatically and forgo the Chart Web control then we need to create a separate page that handles rendering the chart control. In the download available at the end of this article I've created such a page and named it ShowChart.aspx. This page's code starts by creating a Chart object that contains the sales figures chart for the Beverages category for 1997.

'Create the Chart object and set some properties
Dim salesChart As New Chart
salesChart.Width = 500
salesChart.Height = 400

'Plot its data... here we use Scott Allen's ChartBuilder class, but you could
'plot the data programmatically, via data binding, etc. For more info on the
'various plotting techniques, see:
Dim builder = New SalesByCategoryChartBuilder(salesChart)
builder.CategoryName = "Beverages"
builder.OrderYear = 1997

Next, it saves the chart image to a new MemoryStream and then uses the classes in the System.Drawing namespace to add the watermark, "Copyright Northwind Traders."

Using imgStream As New MemoryStream()
   salesChart.SaveImage(imgStream, ChartImageFormat.Png)

   'Add a watermark!
   Dim watermarkText As String = "Copyright Northwind Traders"
   Dim bitmap As Bitmap = bitmap.FromStream(imgStream)

   Dim watermarkFont As New Font(New FontFamily("Verdana"), 18.0, FontStyle.Bold Or FontStyle.Italic)
   Dim myGraphics As Graphics = Graphics.FromImage(bitmap)

   Dim sz As SizeF = myGraphics.MeasureString(watermarkText, watermarkFont)

   Dim X As Single = bitmap.Width / 2 - sz.Width / 2
   Dim Y As Single = bitmap.Height / 2 - sz.Height / 2

   myGraphics.DrawString(watermarkText, watermarkFont, New SolidBrush(Color.DarkMagenta), X, Y)


It then saves the watermarked image to a stream (watermarkedStream), specifies the content type, and sends the contents of this stream to the client.

   'Save the watermarked image to a new stream
   Using watermarkedStream As New MemoryStream
      bitmap.Save(watermarkedStream, ImageFormat.Png)

      'Output the contents of the watermarked image stream
      Response.ContentType = "image/png"
   End Using
End Using

The net effect is that if you visit this page directly from your browser then you see the sales data image. Note that the sales data chart has the watermark "Copyright Northwind Traders."

The sales chart contains a dynamically-added watermark.

To show this chart in a web page you need to add an Image Web control (or <img> element) that references ShowChart.aspx. The following Image Web control exists in the demo file Programmatically.aspx:

<asp:Image ID="imgSalesFigures" runat="server" ImageUrl="~/Demos/Rendering/ShowChart.aspx" />

Emailing A Chart Image

Imagine that instead of showing the chart to a user, you wanted to email the chart to their inbox. Or perhaps you want to still show them the chart, but offer an option to email them the chart. In order to email the chart image to a recipient we need to generate the chart image so that we can either attach it to the email message or embed it within the email message.

The code available for download includes a demo (Programmatically.aspx) that lets the visitor specify the category, year, and their email address. The page then generates the sales chart for the specified category and year and emails it to the entered address. The code for generating the chart image is identical to that used for the watermark demo. In a nutshell, a Chart object is instantiated and the ChartBuilder class (via the SalesByCategoryChartBuilder class) is used to plot the chart data based on the user's selections. Following that, the chart image is saved to a MemoryStream.

Next, a MailMessage is created and configured, and the chart is embedded within the email message and sent to the recipient. The code to accomplish takes about a dozen lines of code and is not central to Microsoft Chart controls, so I am not going to show it in order to conserve space. To see the code, download the working demo available at the end of this article. For more information on working with email in ASP.NET, see my article, Sending Email In ASP.NET, and check out Dave Wanta's collection of System.Net.Mail FAQs.

Long story short, the user gets to configure what sort of report they'd like to have emailed to their inbox...

The user can choose the category and order year, and the report is sent to his inbox!

And, voila, they receive an email with the requested chart.

The chart has arrived in the user's inbox.


Prior to this installment, all of our demos of the Microsoft Chart controls have used the Chart Web control to render the image. However, it is possible to programmatically generate the chart with just a few lines of code. Such functionality is useful in ASP.NET MVC applications, when you need to modify the image before displaying, or when you don't want to display the chart image but work with it in some other fashion (such as sending it to a recipient via email).

Happy Programming!

  • By Scott Mitchell


  • Download the code for this article
  • Further Reading

  • Charting With ASP.NET And LINQ | Download Scott's ChartBuilder class
  • Microsoft Chart Controls to PDF with iTextSharp and ASP.NET MVC
  • Sending Email In ASP.NET
  • System.Net.Mail FAQs: How do I send an email with attachments? | How do I embed images in an email?
  • Article Information
    Article Title: ASP.NET.Using Microsoft's Chart Controls In An ASP.NET Application: Programmatically Generating Chart Images
    Article Author: Scott Mitchell
    Published Date: September 30, 2009
    Article URL:

    Copyright 2014 QuinStreet Inc. All Rights Reserved.
    Legal Notices, Licensing, Permissions, Privacy Policy.
    Advertise | Newsletters | E-mail Offers