Easy Tutorial
❮ Prop Webcontrol Checkbox Checked Control Textbox ❯

ASP.NET Web Pages - Chart Helper


Chart Helper - One of the many useful ASP.NET Web Helpers.


Chart Helper

In previous chapters, you have learned how to use ASP.NET's "Helpers".

Earlier, you were introduced to how to use the "WebGrid Helper" to display data in a grid.

This chapter introduces how to use the "Chart Helper" to display data in a graphical format.

The "Chart Helper" can create charts of different types with various formatting options and labels. It can create standard charts such as area charts, bar charts, column charts, line charts, pie charts, and also more specialized charts like stock charts.

The data displayed in the chart can come from an array, a database, or a file.


Creating a Chart from an Array

The following example shows the code needed to create a chart from array data:

Example

@{ 
var myChart = new Chart(width: 600, height: 400) 

.AddTitle("Employees") 

.AddSeries(chartType: "column",
      xValue: new[] {  "Peter", "Andrew", "Julie", "Mary", "Dave" }, 
      yValues: new[] { "2", "6", "4", "5", "3" }) 

.Write();
}

Creating a Chart from a Database

You can execute a database query and then use the data from the query results to create a chart:

Example

@{ 
var db = Database.Open("SmallBakery"); 
var dbdata = db.Query("SELECT Name, Price FROM Product"); 
var myChart = new Chart(width: 600, height: 400) 
   .AddTitle("Product Sales") 
   .DataBindTable(dataSource: dbdata, xField: "Name")
   .Write();
}

Instead of using the DataBindTable method, another approach is to use AddSeries (see the previous example). DataBindTable is easier to use, but AddSeries is more flexible as you can more explicitly specify the chart and data:

Example

@{ 
var db = Database.Open("SmallBakery"); 
var dbdata = db.Query("SELECT Name, Price FROM Product"); 
var myChart = new Chart(width: 600, height: 400) 
   .AddTitle("Product Sales") 
   .AddSeries(chartType:"Pie",
      xValue: dbdata, xField: "Name",
      yValues: dbdata, yFields: "Price")
   .Write();
}

Creating a Chart from XML Data

A third method to create a chart is to use an XML file as the chart's data:

Example

@using System.Data;
@{
var dataSet = new DataSet();
dataSet.ReadXmlSchema(Server.MapPath("data.xsd"));
dataSet.ReadXml(Server.MapPath("data.xml"));
var dataView = new DataView(dataSet.Tables[0]);
var myChart = new Chart(width: 600, height: 400)

.AddTitle("Sales Per Employee")

.AddSeries("Default", chartType: "Pie",

xValue: dataView, xField: "Name",

yValues: dataView, yFields: "Sales")

.Write();
}
❮ Prop Webcontrol Checkbox Checked Control Textbox ❯