How to Create Google Charts in ASP.Net With JSON

Introduction

This article explains how to work with Google Charts and also how Google Charts are better compared to Microsoft RDLC charts and Crystal Report Charts.

In most websites are static in the HTML and we cannot use our RDLC charts and Crystal Report Charts. Google Charts is useful if you have some static data to display. For that just create that data in JSON format and provide charts to display it.

  • It works fine.
  • Its free to use from Google.
  • Google Charts are very interactive compared to RDLC and Crystal Reports.
  • Easy to customize and design.

You can find a number of articles on this topic but they are not well explained with procedures. Here is a good example, read it once you will be a master.

Clean, Simple, Easy.

For more details visit: Google Charts.

If you want to develop RDLC charts then here is a useful article.

How to Create RDLC Charts and Complete Series of All Charts

This article provides the following 3 examples (my favourite ones):

  1. Columns charts
  2. Pie Charts
  3. Bar Charts

Columns charts

column chart


Pie Charts

pie chart

Bar Charts

barchart

Images are used from: Using Google Charts.

Requirements for Developing Google Charts in ASP.NET

ASP.NET, SQL Server and a reference for the Google jsapi.

Step 1: SQL

In this I will show which table I am using and which type of query I am binding to the Google Charts.

Here I have used the following 2 tables:

  1. PaymentDetails
  2. PlanMaster
In the PaymentDetails table I am storing all the payment related data with PlanID from the PlanMasterTable.

In the PlanMaster table I am storing all Plannames.

Here I am providing a Table Snapshot view. I will provide all the tables script and data for testing.

tables script and data for testing

Here is the query that will get the records and we will bind them to the charts.

It's a normal query I have used. In a real scenario it would have many more tables.

select query

I have created a Stored Procedure for displaying the data.

create procedure

Hey we have now completed the SQL Server part. Now we are moving to C# and ASP.NET.

Step 2: Creating the ASP.NET Web Application

Create a new ASP.NET Web Application named WorkingwithGooglecharts and Select .Net Framework 4.0 when adding the project.

After adding you will get a blank solution with default stuff provided by the ASP.NET Web Application.

First I will show you how to create Column charts.

Add a new page to the project with the name Columncharts.aspx.

column chart aspx page

Step 3: Pass Data to Google Charts

After adding the page, the first step is to pass data to Google Charts.

Google Charts requires data in JSON format. For passing JSON data I am creating WebMethod.

Before WebMethod I have created a class with the name ChartDetails.

It will have the following 2 Properties:
  1. PlanName
  2. PaymentAmount

After adding the class I will now create a WebMethod of type ChartDetails.

Because I will pass a List of ChartDetails to JSON.

get chart data

Then inside WebMethod I have created a SQL Connection for getting data.

connection string

After setting the Connection String, I have written a SQL command of type Stored Producre to get data from SQL Tables into a DataTable.

  1. SqlCommand cmd = new SqlCommand("Usp_Getdata", con);  
  2. cmd.CommandType = CommandType.StoredProcedure;  
  3. SqlDataAdapter da = new SqlDataAdapter();  
  4. da.SelectCommand = cmd;  
  5. DataTable dt = new DataTable();  
  6. da.Fill(dt);  
After filling in data for the DataTable now pass that data into a list of type ChartDetails.
  1. List<ChartDetails> dataList = new List<ChartDetails>();  
  2. foreach (DataRow dtrow in dt.Rows)  
  3. {  
  4.       ChartDetails details = new ChartDetails();  
  5.       details.PlanName = dtrow[0].ToString();  
  6.       details.PaymentAmount = Convert.ToInt32(dtrow[1]);   
  7.       dataList.Add(details);  
  8. }  
After all here is the complete method to be created.
  1. [WebMethod]  
  2. public static List<ChartDetails> GetChartData()  
  3. {  
  4.   
  5.       using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GCConnectionString"].ToString()))  
  6.       {  
  7.             SqlCommand cmd = new SqlCommand("Usp_Getdata", con);  
  8.             cmd.CommandType = CommandType.StoredProcedure;  
  9.             SqlDataAdapter da = new SqlDataAdapter();  
  10.             da.SelectCommand = cmd;  
  11.             DataTable dt = new DataTable();  
  12.             da.Fill(dt);  
  13.   
  14.             List<ChartDetails> dataList = new List<ChartDetails>();  
  15.   
  16.             foreach (DataRow dtrow in dt.Rows)  
  17.             {  
  18.                   ChartDetails details = new ChartDetails();  
  19.                   details.PlanName = dtrow[0].ToString();  
  20.                   details.PaymentAmount = Convert.ToInt32(dtrow[1]);  
  21.   
  22.                   dataList.Add(details);  
  23.             }  
  24.             return dataList;  
  25.       }  
  26. }  
Now we have completed the passing of the data. Now let's move to the design part.

Step 4: Google Charts Design

This is the design part of Google Charts.

First we need to create a goblal variable of Google Charts.
  1. <script type="text/javascript">  
  2.       // Global variable to hold data  
  3.       // Load the Visualization API and the piechart package.  
  4.       google.load('visualization''1', { packages: ['corechart'] });  
  5. </script>  
The next step, after declaring the global varaiable, is to call WebMethod from jQuery to do that.

I have created a function.
  1. $(function ()
  2. {  
  3.    $.ajax(
  4.    {  
  5.       type: 'POST',  
  6.       dataType: 'json',  
  7.       contentType: 'application/json',  
  8.       url: 'ColumnChart.aspx/GetChartData',  
  9.       data: '{}',  
  10.       success: function (response)
  11.       {  
  12.          drawchart(response.d); // calling method  
  13.       },  
  14.   
  15.       error: function ()
  16.       {  
  17.          alert("Error loading data! Please try again.");  
  18.       }  
  19.    });  
  20. })  
This function contains the main thing URL, "ColumnChart.aspx/GetChartData", that will call WebMethod.

And on success I have called another function Draw chart to which I am passing the response that I am getting from Post.
  1. function drawchart(dataValues)
  2. {  
  3.       // Callback that creates and populates a data table,  
  4.       // instantiates the pie chart, passes in the data and  
  5.       // draws it.  
  6.       var data = new google.visualization.DataTable();  
  7.   
  8.       data.addColumn('string''PlanName');  
  9.       data.addColumn('number''PaymentAmount');  
  10.   
  11.       for (var i = 0; i < dataValues.length; i++)   
  12.       {  
  13.             data.addRow([dataValues[i].PlanName, dataValues[i].PaymentAmount] );  
  14.       }  
  15.       // Instantiate and draw our chart, passing in some options  
  16.   
  17.       var chart = new google.visualization.ColumnChart(document.getElementById('chartdiv'));  
  18.   
  19.       chart.draw(data,  
  20.       {  
  21.             title: "Show Google Chart in Asp.net",  
  22.             position: "top",  
  23.             fontsize: "14px",  
  24.             chartArea: { width: '50%' },  
  25.       });  
  26. }  
Declaring datatable and adding Columns into it.
  1. var data = new google.visualization.DataTable();  
  2.   
  3. data.addColumn('string''PlanName');  
  4. data.addColumn('number''PaymentAmount');  
Then using for loop to pass data from Respone into Datatable.
  1. for (var i = 0; i < dataValues.length; i++)   
  2. {  
  3.       data.addRow([dataValues[i].PlanName, dataValues[i].PaymentAmount] );  
  4. }  
Instantiate and draw our chart, passing in some options as in the following:
  1. var chart = new google.visualization.ColumnChart(document.getElementById('chartdiv'));  
Here we pass data and other options that we have to customize the look of the charts.
  1. chart.draw(data,  
  2. {  
  3.       title: "Show Google Chart in Asp.net",  
  4.       position: "top",  
  5.       fontsize: "14px",  
  6.       chartArea: { width: '50%' },  
  7. });  
Here is the complete function view.
  1. <script type="text/javascript">  
  2.         $(function () {  
  3.             $.ajax({  
  4.                 type: 'POST',  
  5.                 dataType: 'json',  
  6.                 contentType: 'application/json',  
  7.                 url: 'ColumnChart.aspx/GetChartData',  
  8.                 data: '{}',  
  9.                 success: function (response) {  
  10.                     drawchart(response.d); // calling method  
  11.                 },  
  12.   
  13.                 error: function () {  
  14.                     alert("Error loading data! Please try again.");  
  15.                 }  
  16.             });  
  17.         })  
  18.   
  19.         function drawchart(dataValues) {  
  20.             // Callback that creates and populates a data table,  
  21.             // instantiates the pie chart, passes in the data and  
  22.             // draws it.  
  23.             var data = new google.visualization.DataTable();  
  24.   
  25.             data.addColumn('string''PlanName');  
  26.             data.addColumn('number''PaymentAmount');  
  27.     
  28.             for (var i = 0; i < dataValues.length; i++)   
  29.             {  
  30.                 data.addRow([dataValues[i].PlanName, dataValues[i].PaymentAmount] );  
  31.             }  
  32.             // Instantiate and draw our chart, passing in some options  
  33.            var chart =  new google.visualization.ColumnChart(document.getElementById('chartdiv'));  
  34.   
  35.        chart.draw(data,  
  36.          {  
  37.              title: "Show Google Chart in Asp.net",  
  38.              position: "top",  
  39.              fontsize: "14px",  
  40.              chartArea: { width: '50%' },  
  41.          });  
  42.         }  
  43.     </script>  
Step 5: Display the Chart

The last thing is to display the chart. I used a div for this and given an id to it.
  1. <body>  
  2.     <form id="form1" runat="server">  
  3.   
  4.      <div id="chartdiv" style="width: 600px; height: 350px;">   
  5.      </div>  
  6.   
  7.     </form>  
  8. </body>  
Step 6: Run

Now just run the application and check it.

Here is the output of a Column Chart.

column chart image

Here is how the data is displayed on charts.

data is displayed on charts

Here are all the charts I have shown you.

all charts

You can download this charts attachment and check it. You will find all the examples and code related to it in details.