Introduction

This article introduces use of the Google Charts API with a database in ASP.NET. Google has a jQuery API for chart and graph visuals. I have explored a little more and used them with a SQL Server database data and simply plunged chart data with jQuery into an aspx page and it works.

At the following URL you will find technical documentation of the Google Charts API:

https://google-developers.appspot.com/chart/

1. Combo charts

The final result will be as shown below.



Step 1

Prepare the data in the SQL Server database as in the following:



Step 2

The following is the Stored Procedure to fetch data required for the chart:

  1. CREATE PROCEDURE dbo.GetData
  2. AS
  3. BEGIN
  4. SELECT *
  5. FROM tbl_data
  6. END

Step 3

The following is the .aspx Page Script:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title>Charts Example</title>
  6. </head>
  7. <body>
  8. <form id="form1" runat="server">
  9. <div>
  10. <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  11. <asp:GridView ID="gvData" runat="server">
  12. </asp:GridView>
  13. <br />
  14. <br />
  15. <asp:Literal ID="ltScripts" runat="server"></asp:Literal>
  16. <div id="chart_div" style="width: 660px; height: 400px;">
  17. </div>
  18. </div>
  19. </form>
  20. </body>
  21. </html>

Step 4

The following is the ..aspx Page code behind:

  1. #region " [ Using ] "
  2. using System;
  3. using System.Web.UI;
  4. using System.Data.SqlClient;
  5. using System.Data;
  6. using System.Configuration;
  7. using System.Text;
  8. #endregion
  9. public partial class _Default : System.Web.UI.Page
  10. {
  11. protected void Page_Load(object sender, EventArgs e)
  12. {
  13. if (!Page.IsPostBack)
  14. {
  15. // Bind Gridview
  16. BindGvData();
  17. // Bind Charts
  18. BindChart();
  19. }
  20. }
  21. private void BindGvData()
  22. {
  23. gvData.DataSource = GetChartData();
  24. gvData.DataBind();
  25. }
  26. private void BindChart()
  27. {
  28. DataTable dsChartData = new DataTable();
  29. StringBuilder strScript = new StringBuilder();
  30. try
  31. {
  32. dsChartData = GetChartData();
  33. strScript.Append(@"<script type='text/javascript'>
  34. google.load('visualization', '1', {packages: ['corechart']});</script>
  35. <script type='text/javascript'>
  36. function drawVisualization() {
  37. var data = google.visualization.arrayToDataTable([
  38. ['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Average'],");
  39. foreach (DataRow row in dsChartData.Rows)
  40. {
  41. strScript.Append("['" + row["Month"] + "'," + row["Bolivia"] + "," +
  42. row["Ecuador"] + "," + row["Madagascar"] + "," + row["Avarage"] + "],");
  43. }
  44. strScript.Remove(strScript.Length - 1, 1);
  45. strScript.Append("]);");
  46. strScript.Append("var options = { title : 'Monthly Coffee Production by Country', vAxis: {title: 'Cups'}, hAxis: {title: 'Month'}, seriesType: 'bars', series: {3: {type: 'area'}} };");
  47. strScript.Append(" var chart = new google.visualization.ComboChart(document.getElementById('chart_div')); chart.draw(data, options); } google.setOnLoadCallback(drawVisualization);");
  48. strScript.Append(" </script>");
  49. ltScripts.Text = strScript.ToString();
  50. }
  51. catch
  52. {
  53. }
  54. finally
  55. {
  56. dsChartData.Dispose();
  57. strScript.Clear();
  58. }
  59. }
  60. /// <summary>
  61. /// fetch data from mdf file saved in app_data
  62. /// </summary>
  63. /// <returns>DataTable</returns>
  64. private DataTable GetChartData()
  65. {
  66. DataSet dsData = new DataSet();
  67. try
  68. {
  69. SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
  70. SqlDataAdapter sqlCmd = new SqlDataAdapter("GetData", sqlCon);
  71. sqlCmd.SelectCommand.CommandType = CommandType.StoredProcedure;
  72. sqlCon.Open();
  73. sqlCmd.Fill(dsData);
  74. sqlCon.Close();
  75. }
  76. catch
  77. {
  78. throw;
  79. }
  80. return dsData.Tables[0];
  81. }
  82. }

Step 5

The following is the .Web.config file:

  1. <?xml version="1.0"?>
  2. <configuration>
  3. <system.web>
  4. <compilation debug="true" targetFramework="4.0"/>
  5. </system.web>
  6. <connectionStrings>
  7. <add name="connectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
  8. </connectionStrings>
  9. </configuration>

Step 6

Run it.



2. Pie Chart

The final result will be as shown below.



Step 1

Prepare the data as in the following:



Step 2

Prepare the Stored Procedure as in the following:

  1. CREATE PROCEDURE GetPieChartData
  2. AS
  3. begin
  4. SELECT *
  5. FROM tbl_Data2
  6. end

Step 3

The following is the .aspx script:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="frmPieChart.aspx.cs" Inherits="frmPieChart" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title></title>
  6. </head>
  7. <body>
  8. <form id="form1" runat="server">
  9. <div>
  10. <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  11. <asp:GridView ID="gvData" runat="server">
  12. </asp:GridView>
  13. <br />
  14. <br />
  15. <asp:Literal ID="ltScripts" runat="server"></asp:Literal>
  16. <div id="piechart_3d" style="width: 900px; height: 500px;">
  17. </div>
  18. </div>
  19. </form>
  20. </body>
  21. </html>

Step 4

The following is the .aspx code behind:

  1. #region " [ Using ] "
  2. using System;
  3. using System.Web.UI;
  4. using System.Data.SqlClient;
  5. using System.Data;
  6. using System.Configuration;
  7. using System.Text;
  8. #endregion
  9. public partial class frmPieChart : System.Web.UI.Page
  10. {
  11. protected void Page_Load(object sender, EventArgs e)
  12. {
  13. if (!Page.IsPostBack)
  14. {
  15. // Bind Gridview
  16. BindGvData();
  17. // Bind Charts
  18. BindChart();
  19. }
  20. }
  21. private void BindGvData()
  22. {
  23. gvData.DataSource = GetChartData();
  24. gvData.DataBind();
  25. }
  26. private void BindChart()
  27. {
  28. DataTable dsChartData = new DataTable();
  29. StringBuilder strScript = new StringBuilder();
  30. try
  31. {
  32. dsChartData = GetChartData();
  33. strScript.Append(@"<script type='text/javascript'>
  34. google.load('visualization', '1', {packages: ['corechart']}); </script>
  35. <script type='text/javascript'>
  36. function drawChart() {
  37. var data = google.visualization.arrayToDataTable([
  38. ['Task', 'Hours of Day'],");
  39. foreach (DataRow row in dsChartData.Rows)
  40. {
  41. strScript.Append("['" + row["Task"] + "'," + row["Hours"] + "],");
  42. }
  43. strScript.Remove(strScript.Length - 1, 1);
  44. strScript.Append("]);");
  45. strScript.Append(@" var options = {
  46. title: 'My Daily Schedule',
  47. is3D: true,
  48. }; ");
  49. strScript.Append(@"var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
  50. chart.draw(data, options);
  51. }
  52. google.setOnLoadCallback(drawChart);
  53. ");
  54. strScript.Append(" </script>");
  55. ltScripts.Text = strScript.ToString();
  56. }
  57. catch
  58. {
  59. }
  60. finally
  61. {
  62. dsChartData.Dispose();
  63. strScript.Clear();
  64. }
  65. }
  66. /// <summary>
  67. /// fetch data from mdf file saved in app_data
  68. /// </summary>
  69. /// <returns>DataTable</returns>
  70. private DataTable GetChartData()
  71. {
  72. DataSet dsData = new DataSet();
  73. try
  74. {
  75. SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
  76. SqlDataAdapter sqlCmd = new SqlDataAdapter("GetPieChartData", sqlCon);
  77. sqlCmd.SelectCommand.CommandType = CommandType.StoredProcedure;
  78. sqlCon.Open();
  79. sqlCmd.Fill(dsData);
  80. sqlCon.Close();
  81. }
  82. catch
  83. {
  84. throw;
  85. }
  86. return dsData.Tables[0];
  87. }
  88. }

Step 5

Run it.