1. Computing

Using the Chart Control in ASP.NET

It's not the same as your average ASP.NET control!

By

For most of the history of ASP.NET, web page programmers had to pay for their charting technology from third party vendors. Since charts are a big part of business web pages, that was a real problem. Microsoft decided that it was a problem that they had to solve. But they weren't able to get the job done until after ASP.NET 3.5 was released, so for that version it had to be downloaded and installed separately. This caused a lot of problems. For one thing, if you used a shared host environment, the host had to install the download, not you. Talking a hosting provider into installing software on their server is not for the timid.

At least it was a free download!

When ASP.NET 4.0 was released, Charts were "in the box" already and much easier to use. And it proved to be a great addition to the feature set of ASP.NET. If you're thinking of using Chart in a shared hosting environment, simply make sure your host supports Framework 4.0 and things should "just work".

To complete the introduction, here's a complete ASP.NET application -- downloadable at the end of the article -- that pulls charts from Microsoft's Northwind database. Since this isn't an article about databases or ADO.NET, nothing except the charts will be explained here. But if you have questions about that, you might find the answers in the downloadable source code.

(Note: Code and ideas for this article are taken from "Pro ASP.NET 4.0 in VB 2010" by permission of the publisher, Apress. I'm the co-author and it's scheduled to be released in October 2010. But this article goes beyond what is in the book!)

To create a chart on your web page, step one is to drag the Chart control from to Toolbox to your web page. This is a critical step! I'll explain why later. But before we get to that, the complete VB code for the application is here:


Imports System.Drawing
Imports System.Web.UI.DataVisualization.Charting
Imports System.Data.SqlClient

Partial Class Charting_TableBinding
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(
        ByVal sender As Object, ByVal e As System.EventArgs
        ) Handles Me.Load
        ' format the chart
        Chart1.BackColor = Color.Gray
        Chart1.BackSecondaryColor = Color.WhiteSmoke
        Chart1.BackGradientStyle = GradientStyle.DiagonalRight
        Chart1.BorderlineDashStyle = ChartDashStyle.Solid
        Chart1.BorderSkin.SkinStyle = BorderSkinStyle.Emboss
        Chart1.BorderlineColor = Color.Gray

        ' format the chart area
        Chart1.ChartAreas(0).BackColor = Color.Wheat
        ' add and format the title
        Chart1.Titles.Add("Table Bound Chart")
        Chart1.Titles(0).Font = New Font("Utopia", 16)
        ' create the connection to the database
        Dim conn As New SqlConnection(
            ConfigurationManager.ConnectionStrings(
                "Northwind"
                ).ConnectionString
            )
        ' define the command
        Dim command As New SqlCommand(
            "SELECT TOP (5) ProductName, UnitsInStock " &
            "FROM Products WHERE (Discontinued = 'FALSE')", conn)
        ' open the command and create the reader
        command.Connection.Open()
        Dim reader As SqlDataReader = command.ExecuteReader()
        ' bind the X and Y values to the default series 
        ' and format the chart
        Chart1.Series(0).Points.DataBindXY(
            reader, "ProductName", reader, "UnitsInStock")
        Chart1.Series(0).ChartType = SeriesChartType.StackedBar

        ' close the reader and the connection
        reader.Close()
        conn.Close()
    End Sub
End Class

The downloadable source contains the Northwind database in the App_Data folder for a complete solution. The program displays this result on the web page.

--------
Click here to display the illustration.
--------

I mentioned earlier that step 1 is to drag the Chart control to your design window. We're going to explore why that's a good idea now. Here's the Chart control in the design window, along with the markup added to the .aspx file by Visual Studio.

--------
Click here to display the illustration.
--------

Notice that, in addition to the ASP.NET markup for the Chart control, Visual Studio has also added a Register statement. At this point, the main purpose is to register "asp" as a TagPrefix so markup such as ...


<asp:Chart ID="Chart1" runat="server">

... will work.

Chart makes more than the usual changes to your environment. Here's the web.config file before the Chart control is added:

--------
Click here to display the illustration.
--------

Here's web.config after the Chart control is added:

--------
Click here to display the illustration.
--------

A lot of the information you can find on the web explains how to deal with the issues that make all the extra information in web.config necessary in the ASP.NET 3.5 environment. If you're running 4.0 now (and you should be) you can safely ignore most of it. Visual Studio now makes the Chart control as painless as possible, but you can still get into trouble by not understanding the limitations. For example, some coders have acquired the habit of simply copying markup from one .aspx file to another (or copying it from a web page into your own code) rather than using the control from the Toolbox. Do this with the Chart control and your web.config won't get updated and your app will crash.

If you have created a website using the .NET 3.5 version of Chart, you have to update web.config. Microsoft offers these instructions:


Add the code section below to the
configuration/runtime/assemblyBinding
element.
If either the <runtime> or <assemblyBinding> parent element does not present, create it.

<configuration>
   ...
   <runtime>
      ...
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         ...
         <dependentAssembly>
            <assemblyIdentity name="System.Web.DataVisualization"
            publicKeyToken="31bf3856ad364e35"/>
            <bindingRedirect oldVersion="3.5.0.0-3.5.0.0"
            newVersion="4.0.0.0"/>
         </dependentAssembly>
         ...
      </assemblyBinding>
      ...
   </runtime>
   ...
</configuration>

You can also fine tune your web page with web.config. For example, Chart works by creating an image file dynamically and then referencing that dynamic file on the web page. Here's the default section of web.config that controls how that happens:


<appSettings>
     <add key="ChartImageHandler"
      value="storage=file;timeout=20;dir=c:\TempImageFiles\;" />
</appSettings> 

You can control where and how that virtual image is managed by changing the settings here. If your app is creating lots of charts, it could make a huge difference in performance.

Download the source code for the application above here:

  1. About.com
  2. Computing
  3. Visual Basic
  4. ASP.NET HUB
  5. The Chart Control in Visual Basic 2010 and ASP.NET 4.0

©2014 About.com. All rights reserved.