Skip to content

How To dynamically Add row To Google Chart with for loop

I Have Problem in Google chart.

I am using asp.net Mvc. After I fetch data from controller, I pass it into Google chart .

When i use manual data, for example:

['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Papua New Guinea', 'Rwanda', 'Average'],
['2004/05',  165,      938,         522,             998,           450,      614.6],

It Show me correctly .

But how can i add my data dynamically into Google chart ?

This is my code:

for (var i = 0; i < chartsdata.length; i++) {

    var data = google.visualization.arrayToDataTable([
        ['Element', 'Density', {role: 'style'}],
        [chartsdata[i].MonthValue, chartsdata[i].CountValue, '#b87333']
    ]);

    var options = {
        title: ''
    };

    var chart = new google.visualization.ComboChart(document.getElementById('chartdiv'));
    chart.draw(data, options);
}

Answer

The way you are doing is wrong.You should do something like below:

 var data=[];
 var Header= ['Element', 'Density', { role: 'style' }];
 data.push(Header);
 for (var i = 0; i < chartsdata.length; i++) {
      var temp=[];
      temp.push(chartsdata[i].MonthValue);
      temp.push(chartsdata[i].CountValue);

      data.push(temp);
  }
var chartdata = new google.visualization.arrayToDataTable(data);