Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

ASP.NET Web Pages Chart

ASP.NET Web Pages - Chart Helper


The Chart helper - one of many useful ASP.NET Web helpers.


Chart Helper

In previous chapters, you have learned how to use ASP.NET "helpers".

Earlier, you learned how to use the "WebGrid helper" to display data in a grid.

This chapter introduces how to use the "Chart helper" to display data graphically.

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

chartchart

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


Create a Chart from an Array

The example below shows the code needed to display a chart based on 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();
}

Run Example »


Create a Chart from a Database

You can execute a database query and then use the data from the query result 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();
}

Run Example »

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

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();
}

Run Example »


Create a Chart from XML Data

A third way to create a chart is to use an XML file as the chart 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();}
}

Run Example »