Shubham Mehta
Shubham Mehta

Reputation: 89

Changing chart data dynamically with C# from SQL database

This is my chart code.

<!-- Graphs -->
<script src="../Scripts/Chart.min.js"></script>
<script>
  var ctx = document.getElementById("myChart");
  var myChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
      datasets: [{
        data: [1, 6, 2, 5, 9, 5, 6],
        label: "Issues Resolved",
        lineTension: 0,
        backgroundColor: 'transparent',
        borderColor: '#007bff',
        borderWidth: 4,
        pointBackgroundColor: '#007bff'
      }, {
                data: [8, 5, 8, 6, 0, 2, 2],
                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>

This graph, though working fine, is static. What I want to ask is whether I can dynamically change the data (of which I'll always have 7 values, for each day of the week) in my datasets (of which I'll always have 2 values, for issues raised and issues resolved) from my .aspx.cs (which will get this data from my SQL Database) at runtime. And if so, how?

Thank you for your help.

Upvotes: 0

Views: 2689

Answers (4)

Mohsin Mehmood
Mohsin Mehmood

Reputation: 4236

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);

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

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
});

Upvotes: 1

A Ghazal
A Ghazal

Reputation: 2823

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...

Upvotes: 0

Alec Nunez
Alec Nunez

Reputation: 11

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;
}

Upvotes: 1

Adam H
Adam H

Reputation: 1828

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.

Upvotes: 0

Related Questions