Create Charts in ASP.NET

The Microsoft Chart control allows us to easily create many types of charts in Windows applications and in ASP.NET applications.

If you’re using .NET 3.5 (Visual Studio 2008), you will need to download a separate installer from Microsoft’s download page. Optionally, you can also download an Add-on for Visual Studio 2008 that will add the Chart control to the Toolbox.

Starting with .NET 4 (Visual Studio 2010), the Microsoft Chart control is part of the framework. You don’t need to download anything else.

Create a new ASP.NET Web Application and add a reference to System.Web.DataVisualization.

System.Web.DataVisualization

If you’re using Visual Studio 2010 or if you installed the Add-on for Visual Studio 2008, you’ll see the Chart control in the Toolbox under the Data section.

Chart Control

Before you can start using the Chart control, you need to set up an http handler in the web.config for the path ChartImg.axd.

For .NET 3.5, add the following inside the <system.web> section.

    <httpHandlers>
      <add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
    </httpHandlers>

And here’s the one for .NET 4.

    <httpHandlers>
      <add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
    </httpHandlers>

This is how the browser will request the chart to the web server. If you don’t add this http handler to the web.config, you’ll get the following error.

Error executing child request for ChartImg.axd

To start using the Chart control in a page, you’ll need to register it first like this:

<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>

If you want to make the control available to all the pages in your application, you can register the Chart control in the web.config:

<pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      </controls>
    </pages>

Change the assembly version if you’re using .NET 3.5.

Let’s add a couple of charts to a web page. I’ll use the Default.aspx page.

<%@ Page Title="Chart Sample" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="ChartSample._Default" %>

<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

    <asp:Chart ID="Chart1" runat="server" Width="400px" Height="300px" Palette="BrightPastel" BackColor="Silver" BackSecondaryColor="White" BackGradientStyle="TopBottom">
        <Series>
            <asp:Series Name="Series1" ChartType="Column" ChartArea="ChartArea1">
            </asp:Series>
        </Series>
        <ChartAreas>
            <asp:ChartArea Name="ChartArea1" BackSecondaryColor="White" BackColor="Gainsboro" BackGradientStyle="DiagonalLeft">
            </asp:ChartArea>
        </ChartAreas>
        <Titles>
            <asp:Title Text="Sales per Month" />
        </Titles>
        <BorderSkin SkinStyle="Emboss" />
    </asp:Chart>

    <asp:Chart ID="Chart2" runat="server" Width="400px" Height="300px" Palette="BrightPastel" BackColor="Silver" BackSecondaryColor="White" BackGradientStyle="TopBottom">
        <Series>
            <asp:Series Name="Series1" ChartType="Pie" ChartArea="ChartArea1" Legend="Default" Label="#PERCENT{P2}" LegendText="#VALX">
            </asp:Series>
        </Series>
        <ChartAreas>
            <asp:ChartArea Name="ChartArea1" BackColor="Transparent">
            </asp:ChartArea>
        </ChartAreas>
        <Titles>
            <asp:Title Text="Sales by Department" />
        </Titles>
        <Legends>
            <asp:Legend Name="Default" BackSecondaryColor="White" BackColor="Gainsboro" BackGradientStyle="DiagonalLeft" />
        </Legends>
        <BorderSkin SkinStyle="Emboss" />
    </asp:Chart>

</asp:Content>

The first chart will be a column chart, and the second one will be a pie chart. Take a look at how we set the dimensions, the colors, and the titles and label formats. We also set up legends for the second chart.

We could also define the lists of points for our series here. But in this case, we’ll add the points in the code behind.

Let’s define the data we’ll use to populate the charts. I’ll show you two types of data sources we can use to populate the points for the charts. Add a new class to the project and name it DataAccess.

For the first chart, we’ll use a DataTable to represent data from a database. For the second chart, we’ll use a collection of objects that would represent a model in our application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

namespace ChartSample
{
    public class DataAccess
    {
        public static DataTable GetSalesPerMonth()
        {
            DataTable dt = new DataTable();

            DataColumn col = new DataColumn();
            col.ColumnName = "Month";
            col.DataType = typeof(String);
            dt.Columns.Add(col);

            col = new DataColumn();
            col.ColumnName = "Sales";
            col.DataType = typeof(Decimal);
            dt.Columns.Add(col);

            DataRow row = dt.NewRow();
            row["Month"] = "July";
            row["Sales"] = 122000m;
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["Month"] = "August";
            row["Sales"] = 96000m;
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["Month"] = "September";
            row["Sales"] = 135000m;
            dt.Rows.Add(row);

            dt.AcceptChanges();

            return dt;
        }

        public static IEnumerable<Sale> GetSalesByDepartment()
        {
            List<Sale> sales = new List<Sale>();

            Sale s = new Sale();
            s.Department = "Service";
            s.Sales = 35000m;
            sales.Add(s);

            s = new Sale();
            s.Department = "Stores";
            s.Sales = 60000m;
            sales.Add(s);

            s = new Sale();
            s.Department = "Internet";
            s.Sales = 40000m;
            sales.Add(s);

            return sales;
        }
    }

    public class Sale
    {
        public String Department { get; set; }
        public Decimal Sales { get; set; }
    }
}

In a real application, these methods would probably read data from a database, but to keep the sample simple, I’ve hard coded some data. The first method returns a DataTable, while the second method returns a list of objects.

Now open the Default.aspx.cs file and add the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace ChartSample
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindCharts();
            }
        }

        private void BindCharts()
        {
            DataTable dt = DataAccess.GetSalesPerMonth();
            DataView data = new DataView(dt);
            Chart1.Series["Series1"].Points.DataBind(data, "Month", "Sales", "");

            IEnumerable<Sale> data2= DataAccess.GetSalesByDepartment();
            Chart2.Series["Series1"].Points.DataBind(data2, "Department", "Sales", "");
        }
    }
}

A chart can have multiple series, and a series is nothing more that a collection of points. Each point has an X value and a Y value.

We could use a loop to add each point to the Points property. This would probably be the case if we were capturing the values from the user.

When we already have data from another source, such as a database, we simply use the DataBind method.

The first parameter is a IEnumerable collection, such as a List. This is why we can’t use the DataTable object directly and need to create a DataView object.

The second parameter is the name of the field or property for the X values, and the third parameter the field or property for the Y values.

Run the project.

Chart Sample

Please leave your comments.

Get Free Updates
Related Posts
Comments