This tutorial uses the new MS Chart to render a column graph from a DataTable in C# and ASP.NET 3.5
In this tutorial, we will be looking at the new addition to the .NET Framework, MS Charts. We will be rendering a bar graph from a DataTable, and show just how easy Microsoft make it for us to do so. We can use the Chart control like other ASP.NET data controls, and assign it a data source.
Please note that MS Chart will not work in ASP.NET 2.0 and below. If you are working within 3.5 or 4.0, then you can download the MS Chart extension at the following address:
http://code.msdn.microsoft.com/mschart
For this example, we will programmatically instantiate and populate a DataTable on page load. In a real-world application, the chart would be fed with data from an external source, like a database or XML file. However, the principle will remain the same.
There is not just one way to render a Chart in ASP.NET. Using MS Chart, we can either give it a data source like any other data control, or we can loop through the data values and plot each point on the graph individually. In this example, we will show you both ways.
Before we begin anything, and even start up Visual Studio.NET, we first need to download and install the Chart extension. You can download from the above web address, and the install is a quick process - consisting of two EXEs.
Once installed, we can start up Visual Studio and create a new Web Application. Then the first thing to do is add two references in the Web.config:
In system.web/httpHandlers, add the following:
|
<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"/>
|
Then in system.webserver/handlers, add this:
|
<add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
|
Now that we have added these references, we will be able to implement Charts in our ASPX pages. You can add the Chart to the toolbox by right-clicking an empty space on the toolbox and selecting Choose Items, then navigating to the install folder (Program Files/Microsoft Chart Controls/Assemblies). You will want to select the System.Web.DataVisualization.dll
To begin, drag the Chart onto your ASPX page - or add the following code:
<form id="form1" runat="server">
<asp:Chart ID="Chart1" runat="server" Width="550px">
<Series>
<asp:series Name="Series1"></asp:series>
</Series>
<ChartAreas>
<asp:ChartArea Name="ChartArea1">
</asp:ChartArea>
</ChartAreas>
</asp:Chart>
</form>
|
We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!
If you dragged from the toolbox, you will also notice the following added to the top of the page. If you added manually, then this code also needs to be added below the page directive:
|
<%@ Register Assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>
|
We do not need to do anything more to this page, unless we want to change how the graph is displayed. But this tweaking can be left until after you actually can see the graph.
Let's move to the code-behind where we will add our logic to display the graph.
Before we code anything related to the Chart, we need to add the following references:
using System.Web.UI.DataVisualization.Charting;
using System.Data;
|
As mentioned earlier in the tutorial, we are going to hard-code a datatable for use in this example. We will keep it simple and use two columns - Name, and Age:
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);
|
We are using Server Intellect and have found that by far, they are the most friendly, responsive, and knowledgeable support team we've ever dealt with!
On Page_load, we want to set the type of graph we wish to render. For this example, we will use a column graph:
|
Chart1.Series["Series1"].ChartType = SeriesChartType.Column;
|
Now, we will render the graph simply by setting the datasource of the Chart control:
Chart1.DataSource = dt;
Chart1.Series["Series1"].XValueMember = "Name";
Chart1.Series["Series1"].YValueMembers = "Age";
Chart1.DataBind();
|
Here, we are setting which columns within the DataTable are to be set to which axis. Once bound, the data will be displayed.
The other way to achieve this result, which is a little more messy, is to loop through the values and then plot them on the graph one-by-one:
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 < dt.Rows.Count; pointIndex++)
{
plotY = Convert.ToInt16(dt.Rows[pointIndex]["Age"]);
Chart1.Series["Series1"].Points.AddY(plotY);
}
|
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.
Obviously for a computer, this is virtually instantaneous, but the code is a little more cumbersome than simply setting the datasource and axes. Both methods have their disadvantages and advantages with different data sources.
We can clean up the code a little, add a button and load up the graph on button click also utilizing AJAX. Simply add a ScriptManager and UpdatePanel to the ASPX page:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="but_LoadData" runat="server" Text="Load Data" OnClick="but_LoadData_OnClick" />
<br /><br />
<asp:Chart ID="Chart1" runat="server" Width="550px">
<Series>
<asp:series Name="Series1"></asp:series>
</Series>
<ChartAreas>
<asp:ChartArea Name="ChartArea1">
</asp:ChartArea>
</ChartAreas>
</asp:Chart>
</ContentTemplate>
</asp:UpdatePanel>
</form>
|
And then we populate the datatable and set the graph datasource on button click:
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);
Chart1.DataSource = dt;
Chart1.Series["Series1"].XValueMember = "Name";
Chart1.Series["Series1"].YValueMembers = "Age";
Chart1.DataBind();
}
}
|
Looking for more DB ASP.NET Tutorials? Click Here!
|