In this article I will explain with an example, how to create Pie Chart using ChartJS in ASP.Net with C# and VB.Net.
The HTML5 Canvas charts have been implemented using
Chart.js library to which
JSON object is supplied as source of data.
ChartJS plugin
Plase refer the following link for documentation for the
jQuery ChartJS plugin
Database
I have made use of the following table FruitChart with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup consists of following element:
canvas – For displaying chart.
<canvas id="dvChart"></canvas>
Generating JSON string for the Chart in C# and VB.Net
Inside the
Page_Load event handler, the records are fetched from the
FruitChart Table of
SQL Server database using
DataReader.
Then, inside the WHILE loop, a JSON string is generated with following properties:
Name – This property will be displayed in Labels.
Popularity – This property will be used to populate the Chart.
Color – This property will be used to set the color of the various sections of the Chart.
Finally, the JSON string is set into a protected property ChartData, which will be used inside then
JavaScript function for populating the Chart.
C#
protected string ChartData { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT Name, Popularity, Color FROM FruitChart";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
string data = "[";
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
data += "{";
data += string.Format("Name : '{0}', Popularity : {1}, Color : '{2}'", sdr["Name"], sdr["Popularity"], sdr["Color"]);
data += "}, ";
}
data = data.Remove(data.Length - 1, 1);
data += "]";
}
con.Close();
this.ChartData = data;
}
}
}
}
VB.Net
Protected Property ChartData As String
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim query As String = "SELECT Name, Popularity, Color FROM FruitChart"
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(query, con)
con.Open()
Dim data As String = "["
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
data += "{"
data += String.Format("Name : '{0}', Popularity : {1}, Color : '{2}'", sdr("Name"), sdr("Popularity"), sdr("Color"))
data += "}, "
End While
data = data.Remove(data.Length - 1, 1)
data += "]"
End Using
con.Close()
Me.ChartData = data
End Using
End Using
End If
End Sub
Populating Chart using JSON data
Implementing ChartJS plugin
Inside the HTML Markup, the following script files are inherited.
1. jquery.min.js
2. chart.umd.min.js
Inside the
jQuery document ready event handler, the
PopulateChart JavaScript function is called which accepts two parameters:
1. JSON object – The JSON string received from Server-Side (Code-Behind) is converted to JSON object.
2. Chart type – The type of chart.
PopulateChart JavaScript function
Inside this function, the canvas element is referenced and passed as parameter to a newly created object of Chart.js library.
Then, the following other properties are set:
type – the type of Chart.
data – here the Chart Labels, Data and Color are mapped with the JSON values.
options – here the Chart properties such has height, width, etc. and the Legend are specified.
Finally, the legends are defined and the Chart is populated.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
<canvas id="dvChart"></canvas>
<script type="text/javascript">
$(function () {
PopulateChart(eval("<%=this.ChartData%>"), 'pie');
});
function PopulateChart(chartData, chartType) {
var dvChart = $('#dvChart');
var chart = new Chart(dvChart, {
type: chartType,
data: {
labels: chartData.map(fruit => fruit.Name),
datasets: [{
data: chartData.map(fruit => fruit.Popularity),
backgroundColor: chartData.map(fruit => fruit.Color),
borderColor: ['#FFF'],
borderWidth: 1
}]
},
options: {
plugins: {
legend: {
labels: {
boxWidth: 10, // Width of legend box
boxHeight: 10 // Height of legend box
},
display: true, // Show hide legends
position: 'right', //'left', 'right', 'top', 'bottom'
align: 'center', // 'start', 'center', 'end'
reverse: false // Reverse order
}
}
}
});
};
</script>
Screenshot
Demo
Downloads