I want to pass C# datatable result to my chart but I get this error saying 'Argument given to addRows must be either a number or an array'
C#
string result = "";
result = "[";
foreach (DataRow row in dt.Rows)
{
result += "['"+row[0]+"',"+row[1]+"],";
}
result = result.TrimEnd(',')+"]";
txtJsonData.Value = result;
JavaScript
var data = new google.visualization.DataTable();
data.addColumn('string', 'Page');
data.addColumn('number', 'Followers');
var chartData = document.getElementById('txtJsonData').value;
data.addRows(chartData);
SampleData
"[['@flu',401],['@weightloss',1068],['@heartdiseases',223],['@diabetesfacts',356]]"
Meydjer Luzzoli
3933 silver badges10 bronze badges
1 Answer 1
Your variable chartData contains a string. You need to parse it before passing it to addRows.
data.addRows(JSON.parse(chartData));
JSON.parse() takes a string, and will return the corresponding Javascript object. If your code needs to run on Internet Explorer <= 8 (which doesn't include the JSON related functions), you will need to include json2.js, that you can get from https://github.com/douglascrockford/JSON-js
answered Jun 26, 2015 at 12:17
Najkin
9321 gold badge7 silver badges18 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Tweety01
Thanks for reply.I have tried this already but it gives me error Uncaught SyntaxError: Unexpected token " ' "
Najkin
That's because strings in JSON must be enclosed in double quotes, not single quotes. You shouldn't generate JSON by hand like, there are many libraries that will do for you, better and in a safer way.
zoranmax
you have probably found an answer already, in case you haven't as Riokmij mentioned, you can use an external library to generate the JSON literal (server side). One possibility is to use Google DataTable .Net Wrapper which will allow you to translate in a very easy way any List or even System.DataTable into the Google DataTable format.
default