Populate Multi-Series (Multi-Column) Bar Chart from database using jQuery ChartJS Plugin in ASP.Net

Last Reply 3 months ago By dharmendr

Posted 3 months ago

Hi,

I have a snippet in which this person has made use of multi column bar chart using chart.js.

however I want to know that how can I use it in chart.js I want to use this snippet in my asp.net webform

The link is below:

https://codepen.io/Shokeen/pen/NpgbKg

https://codepen.io/bencarmichael/pen/XeYJXJ

The strategy which I am using right now in other charts using chart.js is metioned below and I need the required snippet in this format too.

public class OnGoingAmountToBeBilled
{
    public string[] Labels { get; set; }
    public decimal[] Datas { get; set; }
}

 

        [WebMethod]
        public static OnGoingAmountToBeBilled GetOngoingProjectAmountToBeBilled()
        {
            using (DataTable dt = Snippets.GetData(XQuery(screen, "GetOngoingProjectAmountToBeBilled"), Param("doID", MySession("doID"))))
            {
                OnGoingAmountToBeBilled chartData = new OnGoingAmountToBeBilled();
                string[] label = (dt.AsEnumerable().Select(p => p.Field<string>("ProjName"))).Distinct().ToArray();
                Decimal[] data = (dt.AsEnumerable().Select(p => p.Field<Decimal>("BillAmount"))).ToArray();

                chartData.Labels = label;
                chartData.Datas = data;

                return chartData;
            }
        }

 

Posted 3 months ago

Check the below code for different type of chart for the data as per the link you shared.

HTML

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        DrawChart($('#RadioButtonList1').find('input[type=radio]:checked').val());
    });
    function DrawChart(chartType) {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetChartData",
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var label = response.d.Labels;
                var datasetLabels = response.d.DatasetLabels;
                var datasetDatas = response.d.DatasetDatas;
                var dataSets = [];
                for (var i = 0; i < datasetDatas.length; i++) {
                    var dataSet = {
                        label: datasetLabels[i],
                        backgroundColor: '#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6),
                        borderColor: 'red',
                        borderWidth: 1,
                        data: datasetDatas[i]
                    };
                    dataSets.push(dataSet);
                }
                var ctx = document.getElementById("Chart1").getContext('2d');
                new Chart(ctx, {
                    type: chartType,
                    data: { labels: label, datasets: dataSets },
                    options: {
                        responsive: true,
                        title: { display: true, text: 'Card Details' },
                        legend: { display: true, position: "top" },
                        layout: {
                            padding: { left: 50, right: 50, top: 50, bottom: 50 }
                        },
                        scales: {
                            yAxes: [{ ticks: { beginAtZero: true } }]
                        }
                    }
                });
            }
        });
    }
</script>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="true" RepeatDirection="Horizontal">
    <asp:ListItem Text="Bar" Value="bar" Selected="True" />
    <asp:ListItem Text="Column" Value="horizontalBar" />
    <asp:ListItem Text="Line" Value="line" />
    <asp:ListItem Text="Radar" Value="radar" />
</asp:RadioButtonList>
<hr />
<canvas id="Chart1" style="width: 75%; height: 75%"></canvas>

Code

[WebMethod]
public static ChartData GetChartData()
{
    // Get the datas from database.
    ChartData chartData = new ChartData();
    chartData.Labels = new string[] { "Absence of OB", "Closeness", "Credibility", "Heritage", "M Disclosure", "Provenance", "Reliability", "Transparency" };
    chartData.DatasetLabels = new string[] { "American Express", "Mastercard", "Paypal", "Visa" };
    List<int[]> datasetDatas = new List<int[]>();
    datasetDatas.Add(new int[] { 3, 5, 6, 7, 3, 5, 6, 7 });
    datasetDatas.Add(new int[] { 4, 7, 3, 6, 10, 7, 4, 6 });
    datasetDatas.Add(new int[] { 10, 7, 4, 6, 9, 7, 3, 10 });
    datasetDatas.Add(new int[] { 6, 9, 7, 3, 10, 7, 4, 6 });
    chartData.DatasetDatas = datasetDatas;
    return chartData;
}

public class ChartData
{
    public string[] Labels { get; set; }
    public string[] DatasetLabels { get; set; }
    public List<int[]> DatasetDatas { get; set; }
}

 


Posted 3 months ago

Hi EmadKhan,

Check this example. Now please take its reference and correct your code.

HTML

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        DrawChart($('#RadioButtonList1').find('input[type=radio]:checked').val());
    });
    function DrawChart(chartType) {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetChartData",
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var label = response.d.Labels;
                var datasetLabels = response.d.DatasetLabels;
                var datasetDatas = response.d.DatasetDatas;
                var dataSets = [];
                for (var i = 0; i < datasetDatas.length; i++) {
                    var dataSet = {
                        label: datasetLabels[i],
                        backgroundColor: GetRandomColor(),
                        borderColor: 'red',
                        borderWidth: 1,
                        data: datasetDatas[i]
                    };
                    dataSets.push(dataSet);
                }
                var ctx = document.getElementById("Chart1").getContext('2d');
                new Chart(ctx, {
                    type: chartType,
                    data: { labels: label, datasets: dataSets },
                    options: {
                        responsive: false,
                        title: { display: true, text: 'Project Billing Amount' },
                        legend: { display: true, position: "top" },
                        layout: {
                            padding: { left: 50, right: 50, top: 50, bottom: 50 }
                        },
                        scales: {
                            yAxes: [{ ticks: { beginAtZero: true}}]
                        }
                    }
                });
            }
        });
    }
    function GetRandomColor() {
        var trans = '0.3'; // 80% transparency
        var color = 'rgba(';
        for (var i = 0; i < 3; i++) {
            color += Math.floor(Math.random() * 255) + ',';
        }
        color += trans + ')';
        return color;
    }
</script>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="true" RepeatDirection="Horizontal">
    <asp:ListItem Text="Bar" Value="bar" Selected="True" />
    <asp:ListItem Text="Column" Value="horizontalBar" />
    <asp:ListItem Text="Line" Value="line" />
    <asp:ListItem Text="Radar" Value="radar" />
</asp:RadioButtonList>
<hr />
<canvas id="Chart1" style="width: 800px; height: 400px;"></canvas>

Namespaces

C#

using System.Data;
using System.Web.Services;

VB.Net

Imports System.Data
Imports System.Web.Services

Code

C#

[WebMethod]
public static ChartData GetChartData()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] {
                    new DataColumn("ProjectName", typeof(string)),
                    new DataColumn("AmountToBill",typeof(decimal)),
                    new DataColumn("AmountBilled",typeof(decimal))});

    dt.Rows.Add("Four Seasons", 100000, 50000);
    dt.Rows.Add("Blossoms Hill", 250000, 10000);
    dt.Rows.Add("Future Colony", 10000, 5000);
    dt.Rows.Add("Green Valleys", 100000, 50000);
    dt.Rows.Add("Bahria Town", 40000, 20000);
    dt.Rows.Add("Saadi Town", 400000, 200000);
    dt.Rows.Add("Nazeer Villas", 250000, 10000);
    dt.Rows.Add("Khokar Park", 10000, 5000);
    dt.Rows.Add("ASF Valley", 250000, 10000);
    dt.Rows.Add("Askari Park", 10000, 5000);

    ChartData chartData = new ChartData();

    string[] Labels = (dt.AsEnumerable().Select(p => p.Field<string>("ProjectName"))).Distinct().ToArray();
    chartData.Labels = Labels;

    List<string> datasetLabels = new List<string>();
    for (int i = 1; i < dt.Columns.Count; i++)
    {
        datasetLabels.Add(dt.Columns[i].ColumnName);
    }
    chartData.DatasetLabels = datasetLabels.ToArray();

    List<decimal[]> datasetDatas = new List<decimal[]>();
    for (int i = 0; i < chartData.DatasetLabels.Length; i++)
    {
        List<decimal> data = new List<decimal>();
        for (int j = 0; j < Labels.Length; j++)
        {
            decimal amount = (dt.AsEnumerable().Where(p => p.Field<string>("ProjectName") == Labels[j])
                .Select(p => p.Field<Decimal>(chartData.DatasetLabels[i]))).FirstOrDefault();
            data.Add(amount);
        }
        datasetDatas.Add(data.ToArray());
    }

    chartData.DatasetDatas = datasetDatas;
    return chartData;
}

public class ChartData
{
    public string[] Labels { get; set; }
    public string[] DatasetLabels { get; set; }
    public List<decimal[]> DatasetDatas { get; set; }
}

VB.Net

<WebMethod()>
Public Shared Function GetChartData() As ChartData
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("ProjectName", GetType(String)),
                                          New DataColumn("AmountToBill", GetType(Decimal)),
                                          New DataColumn("AmountBilled", GetType(Decimal))})
    dt.Rows.Add("Four Seasons", 100000, 50000)
    dt.Rows.Add("Blossoms Hill", 250000, 10000)
    dt.Rows.Add("Future Colony", 10000, 5000)
    dt.Rows.Add("Green Valleys", 100000, 50000)
    dt.Rows.Add("Bahria Town", 40000, 20000)
    dt.Rows.Add("Saadi Town", 400000, 200000)
    dt.Rows.Add("Nazeer Villas", 250000, 10000)
    dt.Rows.Add("Khokar Park", 10000, 5000)
    dt.Rows.Add("ASF Valley", 250000, 10000)
    dt.Rows.Add("Askari Park", 10000, 5000)

    Dim chartData As ChartData = New ChartData()
    Dim Labels As String() = (dt.AsEnumerable().[Select](Function(p) p.Field(Of String)("ProjectName"))).Distinct().ToArray()
    chartData.Labels = Labels

    Dim datasetLabels As List(Of String) = New List(Of String)()
    For i As Integer = 1 To dt.Columns.Count - 1
        datasetLabels.Add(dt.Columns(i).ColumnName)
    Next

    chartData.DatasetLabels = datasetLabels.ToArray()
    Dim datasetDatas As List(Of Decimal()) = New List(Of Decimal())()

    For i As Integer = 0 To chartData.DatasetLabels.Length - 1
        Dim data As List(Of Decimal) = New List(Of Decimal)()
        For j As Integer = 0 To Labels.Length - 1
            Dim amount As Decimal = (dt.AsEnumerable().Where(Function(p) p.Field(Of String)("ProjectName") = Labels(j)) _
                                     .Select(Function(p) p.Field(Of Decimal)(chartData.DatasetLabels(i)))).FirstOrDefault()
            data.Add(amount)
        Next

        datasetDatas.Add(data.ToArray())
    Next

    chartData.DatasetDatas = datasetDatas
    Return chartData
End Function

Public Class ChartData
    Public Property Labels As String()
    Public Property DatasetLabels As String()
    Public Property DatasetDatas As List(Of Decimal())
End Class

Screenshot