Rss Feed Like Us on facebook Google Plus

October 28, 2013

Dynamic Google Chart with Asp.net , C Sharp

To display live data on your site using Google chart with asp.net and C#.

  • Google chart tools are powerful, simple to use, and free. Try out our rich gallery of interactive charts and data tools
to create Dynamic Google chart with asp.net, we have to fetch data in Data Table with your preferred back-end server, checkout following steps...
  1. Fetch data in Data Table..
  2. Convert Data into JSON format
  3. Pass JSON Data to Script with web method
  4. Pass JSON Data to google.visualization.DataTable()
  5. Execute Google Chart Script - new google.visualization.ColumnChart("HtmlElementID")
Below is Code Example with three types of chart..(Column Chart, Line Chart, Combo Chart)

1. SCRIPT ( Design Page chart.aspx)

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="//www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load('visualization', '1', { packages: ['corechart'] });
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                url: 'Chart.aspx/GetData',  // Your aspx page url with web method..
                data: '{}',
                success:
                    function (response) {
                        drawVisualization(response.d);
                    }
            });
        })

        function drawVisualization(dataValues) {
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Product Catalogue');
            data.addColumn('number', 'Total Sales');
            data.addColumn('number', 'MOP');
            for (var i = 0; i < dataValues.length; i++) {
                data.addRow([dataValues[i].ColumnName, dataValues[i].Value, dataValues[i].Value2]);
            }
            var options = {
                title: 'Total Sales by Years',
                is3D: true,
                hAxis: { title: 'Product Catalogue', titleTextStyle: { color: 'red'} }
            };
            new google.visualization.ColumnChart(document.getElementById('Div1')).
                draw(data, options);

            new google.visualization.LineChart(document.getElementById('Div2')).
            draw(data, options);

            new google.visualization.ComboChart(document.getElementById('visualization')).
            draw(data, {
                title: 'Total Sales by Years',
                width: 600,
                height: 400,
                is3D: true,
                vAxis: { title: "Total Sales" },
                hAxis: { title: "Produt Catalogue" },
                seriesType: "bars",
                series: { 1: { type: "line"} }
            });
        }        
    </script>


2. HTML ( Design Page chart.aspx)

<body>
    <form id="form1" runat="server">
    <div>
        <div id="visualization" style="width: 600px; height: 350px;">
        </div>
        <div id="Div1" style="width: 600px; height: 350px;">
        </div>
        <div id="Div2" style="width: 600px; height: 350px;">
        </div>
    </div>
    </form>
</body>

3. Code Behind ( chart.aspx.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

public partial class Chart : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static List<Data> GetData()
    {
        SqlConnection conn = new SqlConnection("--YOUR CONNECTION STRING--;");
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        conn.Open();
        string cmdstr = @"select productcatalogue,convert(decimal,sum(localamt)) as totalsales ,convert(decimal,sum(mop)) as mop
                        from [salesdata] group by productcatalogue ";
        SqlCommand cmd = new SqlCommand(cmdstr, conn);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(ds);
        dt = ds.Tables[0];
        List<Data> dataList = new List<Data>();
        string cat = "";
        decimal val = 0;
        decimal val2 = 0;
        foreach (DataRow dr in dt.Rows)
        {
            cat = dr[0].ToString();
            val = Convert.ToDecimal(dr[1]);
            val2 = Convert.ToDecimal(dr[2]);
            dataList.Add(new Data(cat,val,val2));
        }
        return dataList;
    }
}
public class Data
{
    public string ColumnName = "";
    public decimal Value = 0;
    public decimal Value2 = 0;
    public Data(string columnName, decimal value, decimal value2)
    {
        ColumnName = columnName;
        Value = value;
        Value2 = value2;
    }
}


© 2011-2016 Techimpulsion All Rights Reserved.


The content is copyrighted to Tech Impulsion and may not be reproduced on other websites.