Chartjs-Changing chart data dynamically with C# from SQL database

1πŸ‘

I had a similar issue and found this solution. This solution requires you to use using System.Web.Services; and I will leave it to you to implement access to your SQL Database. But hopefully this solution can help you too!

Try using the following in the .ASPX file:

<!-- Graphs -->
<script src="../Scripts/Chart.min.js"></script>
<script>
    $(function () {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            url: 'BackendFileName.aspx/GetChartData', // change to your .aspx filename
            data: '{}',
            success: function (response) {
                drawChart(response.d);
            },

            error: function () {
                console.error("Error loading data! Please try again.");
            }
        });
    })

    function drawChart(dataValues) {
        var issuesResolved = [];
        var issuesRaised = [];
        for (var i = 0; i < dataValues.length; i++) {
            issuesResolved[i] = dataValues[i].issuesResolved;
            issuesRaised[i] = dataValues[i].issuesRaised;
        }
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
                datasets: [{
                    data: issuesResolved,
                    label: "Issues Resolved",
                    lineTension: 0,
                    backgroundColor: 'transparent',
                    borderColor: '#007bff',
                    borderWidth: 4,
                    pointBackgroundColor: '#007bff'
                }, {
                    data: issuesRaised,
                    label: "Issues Raised",
                    lineTension: 0,
                    backgroundColor: 'transparent',
                    borderColor: '#ff8400',
                    borderWidth: 4,
                    pointBackgroundColor: '#ff8400'
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: false
                        }
                    }]
                },
                legend: {
                    display: true
                },
                title: {
                    display: true,
                    text: 'Issues Raised VS Issues Resolved'
                }
            }
        });
    }
</script>

Then add the following methods within backend file:

// Arbitrary class to hold required data from SQL Database
public class ChartDetails
{
    public string IssuesResolved { get; set; }

    public string IssuesRaised { get; set; }

    public ChartDetails()
    {
    }
}

// Method that will be called by JQuery script
[WebMethod]
public static List<ChartDetails> GetChartData()
{
    List<ChartDetails> dataList = new List<ChartDetails>();

    // Access SQL Database Data
    // Assign SQL Data to List<ChartDetails> dataList

    return dataList;
}

0πŸ‘

You most certainly can. Take a look at the documentation here, you just need to implement the AJAX polling to see if the source dataset has changed.

0πŸ‘

I believe what you can do is:

  1. Create a class level string variable in your code behind for holding the serialized array like
    protected string weeklyData;
  2. In Page_Load eventhandler, fetch the data from SQL database and populate an array of numbers int or decimal or floats depending upon your stored data. Lets say you end up with an array containing data

int[] data = [8, 5, 8, 6, 0, 2, 2];

  1. Use the JavaScriptSerializer class to serialize it into a string and assign to weeklyData class variable like this:

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    weeklyData = serializer.Serialize(data);

  2. Assign weeklyData variable in your chart initialization code like:
    data: <%= weeklyData %>,
    enter code here

Another better option will be to write a WEB API service which will expose an endpoint for fetching the weekly data in json array format. Then, you can use jquery get method to get data and then initialize chart

$.get('{enpointurl}', function(weeklyData) {
  //Write chart initialization code here and pass weekly data to chart data option
});

0πŸ‘

Add a hidden field:

<asp:HiddenField ID="hdnLabels" runat="server" Value="" />
<asp:HiddenField ID="hdnData" runat="server" Value="" />

In your chart script add:

labels: [<%= hdnLabels.Value %>],
datasets: [
    {
        data: [ <%= hdnData.Value %>],
        ... other options here,

    }
]

In code behind:

 public void ShowChartData()
    string _data = "";
    string _labels = "";

    ......Loop your SqlDataReader
    ....
    ....
    while (dr.Read())
    {
        _labels = _data + dr["DayOfWeek"].ToString() + @",";
        _data = _data + dr["DayOfWeekValue"].ToString() + @",";
    }

    _labels = _label.Remove(_label.Length - 1);
    _data = _data.Remove(_data.Length - 1);
    hdnLabels.Value = _labels;
    hdnData.Value = _data;
}

Hope this helps…

Leave a comment