locked
How to change color of column in column chart using asp.net? RRS feed

  • Question

  • User-1640542475 posted

    Hi Pls help me to change color of each column in column chart

    Below code works fine in only one color. I have 12 month. How to change the color of each month

    Pls advice me

    Thank you.
    maideen

    Below is my code

    <WebMethod()>
        Public Shared Function LoadTotalQR_Month() As List(Of Object)
    
            Dim query As String = "SELECT SUM(AMOUNT) AS AMOUNT,MonthName,monthno FROM [dbo].[DP_Receipt_Head] " &
                          "WHERE YEARNO =  @YearNo Group BY MonthName,monthno order by Monthno"
            Dim constr As String = ConfigurationManager.ConnectionStrings("ConnectString").ConnectionString
            Dim CharData_AREA As New List(Of Object)()
            CharData_AREA.Add(New Object() {"MonthName", "AMOUNT"})
            Using con As New SqlConnection(constr)
                Using cmd As New SqlCommand(query, con)
                    cmd.Parameters.AddWithValue("@YearNo", Date.Today.Year)
                    con.Open()
                    Using sdr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                        While sdr.Read()
                            CharData_AREA.Add(New Object() {sdr("MonthName"), sdr("AMOUNT")})
                        End While
                    End Using
                    Return CharData_AREA
                End Using
            End Using
    
    
        <script>
            var chartData; // globar variable for hold chart data
            google.load("visualization", "1", { packages: ["corechart"] });
            // Here We will fill chartData
            $(document).ready(function () {
                $.ajax({
                    url: "Default.aspx/LoadTotalQR_Month",
                    data: "",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; chartset=utf-8",
                    success: function (data) {
                        chartData = data.d;
                    },
                    error: function () {
                        alert("Error loading data! Please try again.");
                    }
                }).done(function () {
                    // after complete loading data
                    google.setOnLoadCallback(drawChart_C);
                    drawChart_C();
                });
            });
            function drawChart_C() {
                var data = google.visualization.arrayToDataTable(chartData);
                var options = {
                    title: "",
                    pointSize: 5
                };
                var columnChart = new google.visualization.ColumnChart(document.getElementById('column-chart1'));
                columnChart.draw(data, options);
            }
        </script>

    Friday, April 17, 2020 1:19 AM

Answers

  • User-719153870 posted

    Hi maideen5,

    Bad news, this code works really well on my machine.

    As you can see from my code:

    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

    I used this reference to build the chart, maybe you are using other reference? What about change it to this one i use?

    Best Regard,

    Yang Shen

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 17, 2020 8:26 AM
  • User-1640542475 posted

    Thank you Yang Shen

    Problem solved. based on your advice I have checked and removed <script type="text/javascript" src="https://www.google.com/jsapi"></script>

    now is working fine

    Thank you very much

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 17, 2020 8:33 AM

All replies

  • User409696431 posted

    Read the documentation for the chart you are using.

    Start with https://developers.google.com/chart/interactive/docs/gallery/columnchart#coloring-columns

    Friday, April 17, 2020 1:55 AM
  • User-719153870 posted

    Hi maideen5,

    change color of each column in column chart

    As the Google Chart doc mentioned, you need to add another column { role: 'style' } to your chart data so that it can display with custom color.

    As for how you can achieve this in your specific case which involves Asp.Net, Ajax and Google Chart, please check below demo which is built based on your code:

    Aspx:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="Scripts/jquery-3.4.1.min.js"></script>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
        <script>
            var chartData; // globar variable for hold chart data
            google.load("visualization", "1", { packages: ["corechart"] });
            // Here We will fill chartData
            $(document).ready(function () {
                $.ajax({
                    url: "GoogleChartDemo.aspx/LoadTotalQR_Month",
                    data: "",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; chartset=utf-8",
                    success: function (data) {
                        chartData = data.d;
                    },
                    error: function () {
                        alert("Error loading data! Please try again.");
                    }
                }).done(function () {
                    // after complete loading data
                    google.setOnLoadCallback(drawChart_C);
                    drawChart_C();
                });
            });
            function drawChart_C() {
                var data = google.visualization.arrayToDataTable(chartData);
                data.addColumn({ type: 'string', role: 'style' });
                var ColColors = ["blue", "red", "yellow", "black", "gray", "pink", "#303F9F", "green", "#ff99cc", "gold", "orange","#C51162"];
                for (var i = 0; i < chartData.length-1; i++)
                {
                    data.eg[i].c[2] = { v: ColColors[i] };
                }
                var options = {
                    title: "",
                    pointSize: 5
                };
                var columnChart = new google.visualization.ColumnChart(document.getElementById('column-chart1'));
                columnChart.draw(data, options);
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div id="column-chart1" style="width: 600px; height: 500px">
            </div>
        </form>
    </body>
    </html>

    vb:

    Imports System.Data.SqlClient
    Imports System.Web.Services
    
    Public Class GoogleChartDemo
        Inherits System.Web.UI.Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
        End Sub
    
        <WebMethod()>
        Public Shared Function LoadTotalQR_Month() As List(Of Object)
    
            Dim query As String = "SELECT SUM(AMOUNT) AS AMOUNT,MonthName,monthno FROM [dbo].[DP_Receipt_Head] " &
                          "WHERE YEARNO =  @YearNo Group BY MonthName,monthno order by Monthno"
            Dim constr As String = ConfigurationManager.ConnectionStrings("dbConString").ConnectionString
            Dim CharData_AREA As New List(Of Object)()
            CharData_AREA.Add(New Object() {"MonthName", "AMOUNT"})
            Using con As New SqlConnection(constr)
                Using cmd As New SqlCommand(query, con)
                    cmd.Parameters.AddWithValue("@YearNo", Date.Today.Year)
                    con.Open()
                    Using sdr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                        While sdr.Read()
                            CharData_AREA.Add(New Object() {sdr("MonthName"), sdr("AMOUNT")})
                        End While
                    End Using
                    Return CharData_AREA
                End Using
            End Using
        End Function
    End Class

    sql:

    create table DP_Receipt_Head(id int identity(1,1),Amount int, [MonthName] varchar(50),[monthno] int,[YEARNO] int)
    
    insert into DP_Receipt_Head values(55,'Jan',1,2020),(66,'Feb',2,2020),(77,'Mar',3,2020),(88,'Apr',4,2020),
    (99,'May',5,2020),(45,'Jun',6,2020),(47,'Jul',7,2020),(36,'Aug',8,2020),(58,'Sep',9,2020),(70,'Oct',10,2020),
    (25,'Nov',11,2020),(36,'Dec',12,2020)
    
    select * from DP_Receipt_Head
    
    SELECT SUM(AMOUNT) AS AMOUNT,MonthName,monthno FROM [dbo].[DP_Receipt_Head] WHERE YEARNO =  2020 Group BY MonthName,monthno order by Monthno

    The parts you need to update have been highlighten, as you can see, you need to add a color array to store the colors you want to set to your each column, then you need to add a new column to your chart data, set the color array as the value of your new added column.

    Here's the final result of this demo:

    Best Regard,

    Yang Shen

    Friday, April 17, 2020 6:04 AM
  • User-1640542475 posted

    Thank you  Yang Shen for prompt reply.

    Once added the highlighted code, Graph is displyed empty. Nothing.

    But if remove the highlighted code, it is work as before with single color all column

    Pls advice me.

    thank you

    maideen

    Friday, April 17, 2020 6:39 AM
  • User-719153870 posted

    Hi maideen5,

    Once added the highlighted code, Graph is displyed empty. Nothing.

    Press F12 to open your browser devtools, do you receive any error message?

    Best Regard,

    Yang Shen

    Friday, April 17, 2020 6:48 AM
  • User-1640542475 posted

    No error Yang Shen

    Friday, April 17, 2020 6:55 AM
  • User-719153870 posted

    Hi maideen5,

    This is wierd, which browser you are using and can you share us your result page?

    It's not clear what "Once added the highlighted code, Graph is displyed empty. Nothing." means, a screenshot will help.

    Best Regard,

    Yang Shen

    Friday, April 17, 2020 7:01 AM
  • User-1640542475 posted

    Hi

    screen below is currently working

    http://www.silsnetwork.com/application/screen1.png   Pls see Sales Report Column 1

    Once add the highlighted code, it is not displayed anything, that means empty

    http://www.silsnetwork.com/application/screen2.png   Pls see Sales Report Column 1

    www.silsnetwork.com/application/datasheet.xlsx   some Data

    Thank you

    Friday, April 17, 2020 7:30 AM
  • User-719153870 posted

    Hi maideen5,

    Yes i can see it now. Here are some suggestions:

    1. provide your current code which you added the highlighted part and causes the issue, so that i can reproduce the empty data issue here;
    2. Change the browser, to such as Chrome, see if the issue can be solved, since it might be related to the cache;

    Best Regard,

    Yang Shen

    Friday, April 17, 2020 7:58 AM
  • User-1640542475 posted

    Hi Yang Shen

    I have tested Chrome,IE and Edge, not displayed.

    Here is my code after added the highlighted code

        <script>
            var chartData; // globar variable for hold chart data
            google.load("visualization", "1", { packages: ["corechart"] });
            // Here We will fill chartData
            $(document).ready(function () {
                $.ajax({
                    url: "Chart3.aspx/LoadTotalQR_Month",
                    data: "",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; chartset=utf-8",
                    success: function (data) {
                        chartData = data.d;
                    },
                    error: function () {
                        alert("Error loading data! Please try again.");
                    }
                }).done(function () {
                    // after complete loading data
                    google.setOnLoadCallback(drawChart_C);
                    drawChart_C();
                });
            });
            function drawChart_C() {
                var data = google.visualization.arrayToDataTable(chartData);
                data.addColumn({ type: 'string', role: 'style' });
                var ColColors = ["blue", "red", "yellow", "black", "gray", "pink", "#303F9F", "green", "#ff99cc", "gold", "orange", "#C51162"];
                for (var i = 0; i < chartData.length - 1; i++) {
                    data.eg[i].c[2] = { v: ColColors[i] };
                }
                var options = {
                    title: "",
                    pointSize: 5
                };
                var columnChart = new google.visualization.ColumnChart(document.getElementById('column-chart1'));
                columnChart.draw(data, options);
            }
        </script>

    Pls advice me

    Thank you

    Friday, April 17, 2020 8:19 AM
  • User-719153870 posted

    Hi maideen5,

    Bad news, this code works really well on my machine.

    As you can see from my code:

    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

    I used this reference to build the chart, maybe you are using other reference? What about change it to this one i use?

    Best Regard,

    Yang Shen

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 17, 2020 8:26 AM
  • User-1640542475 posted

    Thank you Yang Shen

    Problem solved. based on your advice I have checked and removed <script type="text/javascript" src="https://www.google.com/jsapi"></script>

    now is working fine

    Thank you very much

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 17, 2020 8:33 AM