Google Charts in ASP.NET Web application

| February 24, 2011 | 9 Comments

Here Goes an Open source code that demonstrates how to integrate Google charts in asp.net web application using Jquery.Following are the screen shots of the sample project.You can change the Drop down list to change chart type.

The project also gives an example of converting  Datatable records in to Json string. Following is the flow of the application.

i) Records are populated in to Datatable.

ii) Datatable is converted to JSON  string and  assigned to a Hidden field.

 protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                DataSet ds = new DataSet();
                DataTable tbl = new DataTable();
                tbl.Columns.Add("test", typeof(string));
                tbl.Columns.Add("rankingtypeid", typeof(int));
                ds.Tables.Add(tbl);
                DataRow row;

                Random r = new Random();

                for (int i = 0; i < 10; i++)
                {

                    row = tbl.NewRow();
                    row[0] = "Test" + i.ToString();
                    row[1] = r.Next(1, 100);

                    tbl.Rows.Add(row);
                }

                //JavaScriptSerializer jSerializer = new JavaScriptSerializer();

                //string Jason1 = jSerializer.Serialize(ds.GetXml());
                jason.Value = GetJSONString(ds.Tables[0]);

            }

        }

        public static string GetJSONString(DataTable Dt)
        {

            string[] StrDc = new string[Dt.Columns.Count];
            string HeadStr = string.Empty;

            for (int i = 0; i < Dt.Columns.Count; i++)
            {

                StrDc[i] = Dt.Columns[i].Caption;

                HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
            }

            HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);

            StringBuilder Sb = new StringBuilder();
            Sb.Append("{\"" + Dt.TableName + "\" : [");

            for (int i = 0; i < Dt.Rows.Count; i++)
            {

                string TempStr = HeadStr;
                Sb.Append("{");

                for (int j = 0; j < Dt.Columns.Count; j++)
                {

                    TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString());
                }

                Sb.Append(TempStr + "},");
            }

            Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
            Sb.Append("]}");

            return Sb.ToString();
        }

iii) Javascript draw chart  is responsible for binding Google chart. It gets the hidden field value and converts it into response object using $.Parse() method.

    
    
    

    

iv) DrawChart function is called  in $.Ready() function for initial loading

v)DrawChart function is called on postbacks in the Begin_Request() method.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GoogleChartASPDEMO._Default" %>

    Sample Google Chart ASP.NET By Umair Ashraf (www.techipost.com)

    
    
    

    

Google Chart Type Column Chart Pie Chart Bar Chart Line Chart

Download Default.aspx

Download Default.aspx.cs

Download project source code

Author :Umair Ashraf  (Umair.ashraf@gmail.com)

Category: ASP.NET

Comments (9)

Trackback URL | Comments RSS Feed

  1. mayur nirmal says:

    I am using this code and we are facing one issue, we are not able to insert watermark in this google chart.

    our code is mentioned below
    —————————————–

    google.load(“visualization”, “1″, { packages: ["corechart"] });
    function drawChart() {
    if (document.getElementById(“”).value != “” || document.getElementById(“”).value!=”") {

    var hf = “”;
    var hf1 = “”;
    var max = 0;
    var max1 = 0;
    var format = “”;
    var format1 = “”;
    var title = “”;

    if (document.getElementById(“”).value == “CR”) {
    title = “INR In Crores”;
    }
    else if (document.getElementById(“”).value == “MN”) {
    title = “INR In Millions”;
    }
    max = document.getElementById(“”);
    max1 = document.getElementById(“”);
    format = document.getElementById(“”);
    format1 = document.getElementById(“”);
    hf = document.getElementById(“”);
    hf1 = document.getElementById(“”);
    var hfcharttype = document.getElementById(“”);
    var response = $.parseJSON(hf.value);
    var response1 = $.parseJSON(hf1.value);
    var data = new google.visualization.DataTable();
    data.addColumn(‘string’, ‘Movie Title’);
    data.addColumn(‘number’, ‘Total’);

    var data4 = new google.visualization.DataTable();
    data4.addColumn(‘string’, ‘Movie Title’);
    data4.addColumn(‘number’, ‘Total’);

    var chart;
    var chart1;

    if (hf.value != “” && hf.value != null) {
    for (var i = 0; i < response.Table1.length; i++) {
    var row = new Array();
    row[0] = response.Table1[i].movietitle;
    row[1] = parseFloat(response.Table1[i].total);
    data.addRow(row);

    var formatter_numeric = new google.visualization.NumberFormat({ formatType: 'decimalSymbol' });

    formatter_numeric.format(data, 1);

    }

    chart = new google.visualization.ColumnChart(document.getElementById('’));

    chart.draw(data, { width: 650, height: 200, title: ”,
    hAxis: { title: ‘Domestic Box Office Collections (NET)’,slantedText: true, titleTextStyle: { color: ‘Orange’, fontName: ”, fontSize: 12, fontStyle: ‘normal’ }, textStyle: { color: ‘Black’, fontName: ”, fontSize: 10} },
    vAxis: { title: title, titleTextStyle: { color: ‘Orange’, fontName: ”, fontSize: 12, fontStyle: ‘bold’ }, textStyle: { color: ‘Black’, fontName: ”, fontSize: 10,fontStyle:’bold’} }, legend: ‘none’,format: format.value, minValue: 0, maxValue: max.value, colors: ['Orange']
    });
    }

    if (hf1.value != “” && hf1.value != null) {
    for (var i = 0; i < response1.Table2.length; i++) {
    var row = new Array();
    row[0] = response1.Table2[i].movietitle;
    row[1] = parseFloat(response1.Table2[i].total);
    data4.addRow(row);

    var formatter_numeric1 = new google.visualization.NumberFormat({ formatType: 'decimalSymbol' });
    formatter_numeric1.format(data4,1);
    }

    chart1 = new google.visualization.ColumnChart(document.getElementById('’));

    chart1.draw(data4, { width: 650, height: 200, title: ”,
    hAxis: { title: ‘International Box Office Collections (GROSS)’,slantedText: true, titleTextStyle: { color: ‘Maroon’, fontName: ”, fontSize: 12, fontStyle: ‘normal’ }, textStyle: { color: ‘Black’, fontName: ”, fontSize: 10} },
    vAxis: { title: ‘USD In Millions’, titleTextStyle: { color: ‘Maroon’, fontName: ”, fontSize: 12, fontStyle: ‘bold’ }, textStyle: { color: ‘Black’, fontName: ”, fontSize: 10, fontStyle: ‘bold’} }, legend: ‘none’, format: format1.value, minValue: 0.001, maxValue: max1.value, colors: ['Maroon']
    });

    }

    }
    }

    $(document).ready(drawChart);

    —————————-

    thanks in advance

  2. JL Agrione says:

    Thanks! Really useful.

  3. jeelani says:

    I have integrated your chart code snippet into my project, but I am getting a js error “hf is null”
    Any help would be appreciated.

  4. Milind Karpe says:

    thanks dude for sharing this information..

  5. Ravi says:

    Nice code. Thanks… but I’m unable to get animation while pageload or after a postback event. struggling with it.

  6. jamil says:

    Thank you very much.
    Its very useful.

  7. Sibeesh says:

    Hi,
    i have gone through your code..but when i run those codes in my web application it shows nothing.i could not see any chart.What i need to do now?

    thank you

  8. Umar says:

    return null jason any help?

Leave a Reply