Install and Use Microsoft Chart Controls to Render a Graph from Data Table in C#

Category: ASP.NET

Using MSChart to Create Graphical Charts in ASP.NET and C#

Introduction

In this article, we will be exploring the new addition to the .NET Framework: Microsoft Chart Controls, and how we can implement full-blown graphs and charts into our Web Applications using only ASP.NET - no need for third party plugins.

What we will learn in this article:

  • How to install MSChart and the Visual Studio add-on;
  • How to implement MSChart in a Web Application to display a graph from database data.

Getting Started
The prerequisites for this article are to download and install MSChart and the add-on for Visual Studio. This tutorial is written with Visual Studio.NET 2008 and ASP.NET 3.5 (Please note, MSChart is not compatible with .NET versions below 3.5
To get started, download the following files from Microsoft:
MSChart.exe
MSChart_VisualStudioAddOn.exe

Another great place to go for MSChart info is http://code.msdn.microsoft.com/mschart, which have code samples of different kinds of graphs and charts.

Once you have the installation files downloaded, install MSChart.exe first, as the add-on requires this to be installed. Both are quick installs, and should take no more than a few minutes, so when both have been successfully installed to your machine, you can start up Visual Studio.
First, create a new Web Application, and now to get the new control into our toolbox, we can right-click on a blank area of it and select Add Tab. Name it something like MSChart:

Try Server Intellect for Windows Server Hosting. Quality and Quantity!

Next, right-click in the new tab and select Choose Items...

We should then see a dialog box like this:


[Click to enlarge]

Click the Browse button and navigate to the Program Files\Microsoft Chart Controls\Assemblies folder. Here you want to add both the Windows.Form and the Web DLLs. Once they're added, they will be available to select in the list box:


[Click to enlarge]

We used over 10 web hosting companies before we found Server Intellect. Their dedicated servers and add-ons were setup swiftly, in less than 24 hours. We were able to confirm our order over the phone. They respond to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.

So once they're added, and checked, they should be available in our toolbox:

Now we can begin using them in our Web Application, but before we do anything else, we need to add the references to the Web.config, something that Visual Studio does not do for us automatically, unfortunately. Open up the Web.config and locate the system.web tag, and then find the httpHandlers tag inside this one and add the following:

Next, locate the system.webServer tags and then the handlers tags within them, and add the following:

Once we have these in place, we can begin on our ASPX page. Let's work on the Default.aspx page and drag a MSChart control from the toolbox onto the page. You will notice that two things are added. First, there is a directive added at the top of the page, which looks something like this:

Secondly, the default MSChart control looks something like this:



Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.

For this example, we do not need to change anything here, as our code-behind will be where the magic happens. So for now, let's leave it like this and move back to the code-behind.
What we will do is create a method to load the data into the chart, and we will then call this method on Page_Load. Now, in a real-world application, we would be grabbing the data from an external source such as a database or XML file, but for this example, we will programmatically create a datatable to use for the graph:

private void FillData()
{
DataTable dt = new DataTable();
DataColumn dc;

dc = new DataColumn();
dc.ColumnName = "Name";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "Age";
dt.Columns.Add(dc);

DataRow dr;
dr = dt.NewRow();
dr["Name"] = "Fred";
dr["Age"] = "54";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Bill";
dr["Age"] = "66";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Rhona";
dr["Age"] = "32";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Peter";
dr["Age"] = "46";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Tina";
dr["Age"] = "26";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Ella";
dr["Age"] = "2";
dt.Rows.Add(dr);
}

Here, we are creating a simple datatable of people, each with a name and an age. There are two ways to bind data to a Chart control: with the DataSource; like other data controls, or by looping through the data source (in this case, a datatable) and plotting each value on the graph. In this article, we will show you both ways. But first, we need to add the following using statement:

using System.Web.UI.DataVisualization.Charting;

Now on to the coding: probably the easiest way to display data as a graph is to set the datasource of the chart like any other data control. We also need to set the labels of the axes, which we can do like so:

Chart1.DataSource = dt;
Chart1.Series["Series1"].XValueMember = "Name";
Chart1.Series["Series1"].YValueMembers = "Age";
Chart1.DataBind();

We use the column names to set the labels of each axis, after setting the datasource. Then we bind the data and it should be displayed as a graph. However, we have one more thing to set - which type of graph do we want? We can set this on Page_Load, or in the method, as well as a few other properties:

Chart1.Series["Series1"].ChartType = SeriesChartType.Column;
Chart1.Series["Series1"]["DrawingStyle"] = "Emboss";
Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
Chart1.Series["Series1"].IsValueShownAsLabel = true;

We will use a Column chart for this example. The DrawingStyle sets the look of the graph, we set the graph to 3D also, and IsValueShownAsLabel shows the actual value of each result above each column. These are all optional settings, which have defaults if they're not set. Now if we run the application, we should get something that looks like this:

A very professional-looking graph with only a few lines of code, which is also very customizable with styles applied to the ASPX tags.
Now the other way to bind the data is to loop through the data. Because we are using a datatable, we will use a for loop:

double plotY = 0;
if(Chart1.Series["Series1"].Points.Count > 0)
{
plotY = Chart1.Series["Series1"].Points[Chart1.Series["Series1"].Points.Count - 1].YValues[0];
}

for (int pointIndex = 0; pointIndex {
plotY = Convert.ToInt16(dt.Rows[pointIndex]["Age"]);
Chart1.Series["Series1"].Points.AddY(plotY);
}

For each value in the datatable, we plot the point on the graph. This will result in a similar graph, without the X-axis labels for each item:

We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.

As an added touch, we can add a button and render the chart on button click. The ASPX page will look something like this:









And the code-behind will look something like this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.DataVisualization.Charting;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void but_LoadData_OnClick(object sender, EventArgs e)
{
Chart1.Series["Series1"].ChartType = SeriesChartType.Column;
Chart1.Series["Series1"]["DrawingStyle"] = "Emboss";
Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
Chart1.Series["Series1"].IsValueShownAsLabel = true;

FillData();
}

private void FillData()
{
DataTable dt = new DataTable();
DataColumn dc;

dc = new DataColumn();
dc.ColumnName = "Name";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "Age";
dt.Columns.Add(dc);

DataRow dr;
dr = dt.NewRow();
dr["Name"] = "Fred";
dr["Age"] = "54";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Bill";
dr["Age"] = "66";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Rhona";
dr["Age"] = "32";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Peter";
dr["Age"] = "46";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Tina";
dr["Age"] = "26";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Ella";
dr["Age"] = "2";
dt.Rows.Add(dr);

double plotY = 0;
if(Chart1.Series["Series1"].Points.Count > 0)
{
plotY = Chart1.Series["Series1"].Points[Chart1.Series["Series1"].Points.Count - 1].YValues[0];
}

for (int pointIndex = 0; pointIndex {
plotY = Convert.ToInt16(dt.Rows[pointIndex]["Age"]);
Chart1.Series["Series1"].Points.AddY(plotY);
}

//Chart1.DataSource = dt;
//Chart1.Series["Series1"].XValueMember = "Name";
//Chart1.Series["Series1"].YValueMembers = "Age";
//Chart1.DataBind();
}
}


Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!