Chartjs-Populate chart.js from data table / SQL result set

0๐Ÿ‘

โœ…

Iโ€™ve created the following Javascript method which is called from the backend

function FillBarChart(names, values, canvasId, graphTitle, labels) {
        var color = Chart.helpers.color;
        var colors = '#' + Math.floor(Math.random() * 16777215).toString(16);
        var collors = 'hsla(' + (Math.floor(Math.random() * 360) + ', 70%, 70%, 1)');
        var chartData = {
            labels: names.split(','),
            datasets: [
                {
                    label: labels,
                    backgroundColor: collors,
                    borderColor: color("#0061ff"),
                    borderWidth: 1,
                    data: values.split(',')
                }
            ]
        };
        var ctx = document.getElementById(canvasId).getContext('2d');
        window.barChart = new Chart(ctx, {
            type: 'bar',
            data: chartData,
            options: {
                responsive: true,
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: graphTitle
                }
            }
        });
    }

The C# lines that trigger this are the following:

StringBuilder javascriptCommands = new StringBuilder();

            HtmlGenericControl canvas = new HtmlGenericControl();
            canvas.TagName = "canvas";
            canvas.Attributes["Height"] = CanvasHeight;
            canvas.ClientIDMode = ClientIDMode.Static;
            canvas.ID = "canvasSales";
            string graphNames = "Previous Year,Current Year";
            string graphValues = MainSession.salesPY + "," + MainSession.salesCY;
            charts.Controls.Add(canvas);
            javascriptCommands.Append("FillBarChart(`" + graphNames + "`,`" + graphValues + "`,`" + canvas.ID + "`,`" + "Grand Total Sales" + "`,`" + "Total Sales Graph" + "`);");

            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "mykey", javascriptCommands.ToString(), true);

MainSession.salesPY and MainSession.salesCY are the needed values, brought from SQL in my case and concatenated as strings, sepparated with a comma.

Leave a comment