none
Gerando grafico chart em c# com banco RRS feed

  • Pergunta

  • Olá, não consigo gerar gráfico.

    Fiz o código mas não funciona alguém pode me ajudar?

     

    OleDbConnection connCarrier = new OleDbConnection();
    
                connCarrier.ConnectionString = Properties.Settings.Default.BDConnectionString;
                connCarrier.Open();
    
                //---------------CAR01
                OleDbCommand cmdCAR01 = new OleDbCommand();
                cmdCAR01.CommandText = "SELECT COUNT (*) FROM DataCarrier WHERE(Posto = 'CAR01')" +
                     "AND AreaResponsavel = 'CARRIER'" + "AND DataDesvio >=" + tempo + " AND DataDesvio <= " + tempo2;
                //"SELECT COUNT(Posto) AS Expr1, Posto FROM DataCarrier WHERE(Posto = 'CAR01') GROUP BY Posto"
    
                cmdCAR01.CommandType = CommandType.Text;
                cmdCAR01.Connection = connCarrier;
                int CAR01;
                int TTCAR01;
                TTCAR01 = (int)cmdCAR01.ExecuteScalar();
                CAR01 = TTCAR01;
    
                OleDbCommand cmdTotal01 = new OleDbCommand();
                cmdTotal01.CommandText = "SELECT COUNT(*) FROM DataCarrier WHERE(Posto = 'CAR01')" +
                     "AND AreaResponsavel = 'CARRIER'" + "AND DataDesvio >=" + tempo + " AND DataDesvio <= " + tempo2;
                cmdTotal01.CommandType = CommandType.Text;
                cmdTotal01.Connection = connCarrier;
                OleDbDataAdapter daTotal = new OleDbDataAdapter(cmdTotal01);
                DataSet dsTotal = new DataSet();
                int CAR01T;
                int TTotal01;
                TTotal01 = (int)cmdTotal01.ExecuteScalar();
                CAR01T = TTotal01;
    
       string[] XValues = { "CAR01"};
    
    
                double[] YValues = {TTCAR01};
    
                double[] YValues2 = {TTotal01};
    
                chart1.Series[0].Points.DataBindXY(XValues, YValues);
                chart1.Series[1].Points.DataBindY(YValues2);
                chart1.ChartAreas[0].AxisX.LabelStyle.Angle = -45;
                chart1.ChartAreas[0].InnerPlotPosition.Height = 90;
                chart1.ChartAreas[0].InnerPlotPosition.Width = 95;
                chart1.ChartAreas[0].InnerPlotPosition.X = 5;
                chart1.ChartAreas[0].InnerPlotPosition.Y = 0;
    
                connCarrier.Close();
    
    
    


    • Editado Marcos SJ terça-feira, 2 de fevereiro de 2016 11:54 Edição
    segunda-feira, 1 de fevereiro de 2016 23:53

Respostas

  • Boa tarde Willians Fernando,

    Seu código me parece suspeito.

    Por favor, sugiro que olhe o método abaixo e faça as alterações necessárias, visto que esse exemplo é mais robusto e segue as boas práticas de programação.

    public class Data
    
    {
    
        public string ColumnName = "";
    
        public int Value = 0;
    
     
    
        public Data(string columnName, int value)
    
        {
    
            ColumnName = columnName;
    
            Value = value;
    
        }
    
    }    
    
              Here we’ve to create a WebMethod to get the data from server. 
    
        [WebMethod]
    
        public static List<Data> GetData()
    
        {
    
            SqlConnection conn = new SqlConnection("Data Source=SPIDER;Initial                                                                                                    Catalog=Northwind;Integrated Security=True");
    
            DataSet ds = new DataSet();
    
            DataTable dt = new DataTable();
    
            conn.Open();
    
            string cmdstr = "select top 5 Country, COUNT(CompanyName) [Total Suppliers] from                                           [Suppliers] group by Country";
    
            SqlCommand cmd = new SqlCommand(cmdstr, conn);
    
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
    
            adp.Fill(ds);
    
            dt = ds.Tables[0];
    
            List<Data> dataList = new List<Data>();
    
            string cat="";
    
            int val=0;
    
            foreach (DataRow dr in dt.Rows)
    
            {
    
                cat=dr[0].ToString();
    
                val=Convert.ToInt32( dr[1]);
    
                dataList.Add(new Data(cat, val));
    
            }
    
            return dataList;
    
        }
    
             
    
    Here we’ve to use following code to load google JSAPI and JQuery libraries
    
         <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript">      </script>
    
        <script type="text/javascript" src="//www.google.com/jsapi"></script>
    
     
    
    Then we’ve to use following code to load Google visualization and package libraries
    
    <script type="text/javascript">
    
            google.load('visualization', '1', { packages: ['corechart'] });
    
    </script>
    
     
    
    Here I’ll make Ajax call from client to get json object with containing data to be displayed
    
    $(document).ready(function () {
    
                $.ajax({
    
                    type: 'POST',
    
                    dataType: 'json',
    
                    contentType: 'application/json',
    
                    url: 'Default.aspx/GetData',
    
                    data: '{}',
    
                    success:
    
                        function (response) {
    
                            drawVisualization(response.d);
    
                        }
    
                });
    
            })
    
     
    
    Here is the function that can be used to draw the chart
    
    function drawVisualization(dataValues) {
    
                var data = new google.visualization.DataTable();
    
                data.addColumn('string', 'Column Name');
    
                data.addColumn('number', 'Column Value'); 
    
                for (var i = 0; i < dataValues.length; i++) {
    
                    data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
    
                } 
    
                new google.visualization.PieChart(document.getElementById('visualization')).
    
                    draw(data, { title: "Google Chart demo" });
    
            }
    
     
    
    Here we need to create a div tag that would be displayed Google chart
    
    <div id="visualization" style="width: 600px; height: 350px;">
    
    </div>
    
     
    
    Designer source code:
    
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 
    
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <head runat="server">
    
        <title></title>
    
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    
        <script type="text/javascript" src="//www.google.com/jsapi"></script>
    
        <script type="text/javascript">
    
            google.load('visualization', '1', { packages: ['corechart'] });
    
        </script>
    
        <script type="text/javascript">
    
            $(document).ready(function () {
    
                $.ajax({
    
                    type: 'POST',
    
                    dataType: 'json',
    
                    contentType: 'application/json',
    
                    url: 'Default.aspx/GetData',
    
                    data: '{}',
    
                    success:
    
                        function (response) {
    
                            drawVisualization(response.d);
    
                        } 
    
                });
    
            })
    
     
    
            function drawVisualization(dataValues) {
    
                var data = new google.visualization.DataTable();
    
                data.addColumn('string', 'Column Name');
    
                data.addColumn('number', 'Column Value'); 
    
                for (var i = 0; i < dataValues.length; i++) {
    
                    data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
    
                } 
    
                new google.visualization.PieChart(document.getElementById('visualization')).
    
                    draw(data, { title: "Google Chart demo" });
    
            }        
    
        </script>
    
    </head>
    
    <body>
    
        <form id="form1" runat="server">
    
        <div id="visualization" style="width: 600px; height: 350px;">
    
        </div>
    
        </form>
    
    </body>
    
    </html>
    
      
    
    Code Behind:
    
    using System;
    
    using System.Collections.Generic;
    
    using System.Linq;
    
    using System.Web;
    
    using System.Web.UI;
    
    using System.Web.UI.WebControls;
    
    using System.Data;
    
    using System.Data.SqlClient;
    
    using System.Web.Services;
    
    public partial class _Default : System.Web.UI.Page
    
    {
    
        protected void Page_Load(object sender, EventArgs e)
    
        {
    
        }  
    
        [WebMethod]
    
        public static List<Data> GetData()
    
        {
    
            SqlConnection conn = new SqlConnection("Data Source=SPIDER;Initial                                                                                            Catalog=Northwind;Integrated Security=True");
    
            DataSet ds = new DataSet();
    
            DataTable dt = new DataTable();
    
            conn.Open();
    
            string cmdstr = "select top 5 Country, COUNT(CompanyName) [Total Suppliers] from                                           [Suppliers] group by Country";
    
            SqlCommand cmd = new SqlCommand(cmdstr, conn);
    
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
    
            adp.Fill(ds);
    
            dt = ds.Tables[0];
    
            List<Data> dataList = new List<Data>();
    
            string cat="";
    
            int val=0;
    
            foreach (DataRow dr in dt.Rows)
    
            {
    
                cat=dr[0].ToString();
    
                val=Convert.ToInt32( dr[1]);
    
                dataList.Add(new Data(cat, val));
    
            }
    
            return dataList;
    
        }
    
    }
    
    public class Data
    
    {
    
        public string ColumnName = "";
    
        public int Value = 0; 
    
        public Data(string columnName, int value)
    
        {
    
            ColumnName = columnName;
    
            Value = value;
    
        }
    
    }   

    Atenciosamente,




    Roberto Alves

    Por favor, lembre-se de Marcar como Resposta as postagens que resolveram o seu problema. Essa é uma maneira comum de reconhecer aqueles que o ajudaram e fazer com que seja mais fácil para os outros visitantes encontrarem a resolução mais tarde.



    • Editado Roberto AB Filho quarta-feira, 3 de fevereiro de 2016 18:19
    • Marcado como Resposta Marcos SJ quinta-feira, 4 de fevereiro de 2016 15:15
    quarta-feira, 3 de fevereiro de 2016 18:18

Todas as Respostas

  • Bom dia Willians Fernando,

    O que quer dizer com "não funciona"?

    Qual seria o problema/erro com a linguagem que está o impedindo de "gerar gráfico"?

    Atenciosamente


    Marcos SJ

    Esse conteúdo e fornecido sem garantias de qualquer tipo, seja expressa ou implícita

    MSDN Community Support

    Por favor, lembre-se de Marcar como Resposta as postagens que resolveram o seu problema. Essa é uma maneira comum de reconhecer aqueles que o ajudaram e fazer com que seja mais fácil para os outros visitantes encontrarem a resolução mais tarde.

    terça-feira, 2 de fevereiro de 2016 11:55
  • Olá,

    estou tentando pegar os dados de um banco de dados via código e mostrar esses dados em um chart.

    terça-feira, 2 de fevereiro de 2016 23:27
  • Olá,

    estou tentando pegar os dados de um banco de dados via código e mostrar esses dados em um chart.

    Qual tipo, tem algum exemplo ?
    É para Windows Forms?

    Qual controle tu usa?


    Fulvio C

    terça-feira, 2 de fevereiro de 2016 23:39
  • é para Windows form sim 

    este é o código

    OleDbConnection connCarrier = new OleDbConnection();
    
                connCarrier.ConnectionString = Properties.Settings.Default.BDConnectionString;
                connCarrier.Open();
    
                //---------------CAR01
                OleDbCommand cmdCAR01 = new OleDbCommand();
                cmdCAR01.CommandText = "SELECT COUNT (*) FROM DataCarrier WHERE(Posto = 'CAR01')" +
                     "AND AreaResponsavel = 'CARRIER'" + "AND DataDesvio >=" + tempo + " AND DataDesvio <= " + tempo2;
                //"SELECT COUNT(Posto) AS Expr1, Posto FROM DataCarrier WHERE(Posto = 'CAR01') GROUP BY Posto"
    
                cmdCAR01.CommandType = CommandType.Text;
                cmdCAR01.Connection = connCarrier;
                int CAR01;
                int TTCAR01;
                TTCAR01 = (int)cmdCAR01.ExecuteScalar();
                CAR01 = TTCAR01;
    
                OleDbCommand cmdTotal01 = new OleDbCommand();
                cmdTotal01.CommandText = "SELECT COUNT(*) FROM DataCarrier WHERE(Posto = 'CAR01')" +
                     "AND AreaResponsavel = 'CARRIER'" + "AND DataDesvio >=" + tempo + " AND DataDesvio <= " + tempo2;
                cmdTotal01.CommandType = CommandType.Text;
                cmdTotal01.Connection = connCarrier;
                OleDbDataAdapter daTotal = new OleDbDataAdapter(cmdTotal01);
                DataSet dsTotal = new DataSet();
                int CAR01T;
                int TTotal01;
                TTotal01 = (int)cmdTotal01.ExecuteScalar();
                CAR01T = TTotal01;
    
       string[] XValues = { "CAR01"};
    
    
                double[] YValues = {TTCAR01};
    
                double[] YValues2 = {TTotal01};
    
                chart1.Series[0].Points.DataBindXY(XValues, YValues);
                chart1.Series[1].Points.DataBindY(YValues2);
                chart1.ChartAreas[0].AxisX.LabelStyle.Angle = -45;
                chart1.ChartAreas[0].InnerPlotPosition.Height = 90;
                chart1.ChartAreas[0].InnerPlotPosition.Width = 95;
                chart1.ChartAreas[0].InnerPlotPosition.X = 5;
                chart1.ChartAreas[0].InnerPlotPosition.Y = 0;
    
                connCarrier.Close();


    terça-feira, 2 de fevereiro de 2016 23:51
  • é para Windows form sim 

    este é o código

    OleDbConnection connCarrier = new OleDbConnection();
    
                connCarrier.ConnectionString = Properties.Settings.Default.BDConnectionString;
                connCarrier.Open();
    
                //---------------CAR01
                OleDbCommand cmdCAR01 = new OleDbCommand();
                cmdCAR01.CommandText = "SELECT COUNT (*) FROM DataCarrier WHERE(Posto = 'CAR01')" +
                     "AND AreaResponsavel = 'CARRIER'" + "AND DataDesvio >=" + tempo + " AND DataDesvio <= " + tempo2;
                //"SELECT COUNT(Posto) AS Expr1, Posto FROM DataCarrier WHERE(Posto = 'CAR01') GROUP BY Posto"
    
                cmdCAR01.CommandType = CommandType.Text;
                cmdCAR01.Connection = connCarrier;
                int CAR01;
                int TTCAR01;
                TTCAR01 = (int)cmdCAR01.ExecuteScalar();
                CAR01 = TTCAR01;
    
                OleDbCommand cmdTotal01 = new OleDbCommand();
                cmdTotal01.CommandText = "SELECT COUNT(*) FROM DataCarrier WHERE(Posto = 'CAR01')" +
                     "AND AreaResponsavel = 'CARRIER'" + "AND DataDesvio >=" + tempo + " AND DataDesvio <= " + tempo2;
                cmdTotal01.CommandType = CommandType.Text;
                cmdTotal01.Connection = connCarrier;
                OleDbDataAdapter daTotal = new OleDbDataAdapter(cmdTotal01);
                DataSet dsTotal = new DataSet();
                int CAR01T;
                int TTotal01;
                TTotal01 = (int)cmdTotal01.ExecuteScalar();
                CAR01T = TTotal01;
    
       string[] XValues = { "CAR01"};
    
    
                double[] YValues = {TTCAR01};
    
                double[] YValues2 = {TTotal01};
    
                chart1.Series[0].Points.DataBindXY(XValues, YValues);
                chart1.Series[1].Points.DataBindY(YValues2);
                chart1.ChartAreas[0].AxisX.LabelStyle.Angle = -45;
                chart1.ChartAreas[0].InnerPlotPosition.Height = 90;
                chart1.ChartAreas[0].InnerPlotPosition.Width = 95;
                chart1.ChartAreas[0].InnerPlotPosition.X = 5;
                chart1.ChartAreas[0].InnerPlotPosition.Y = 0;
    
                connCarrier.Close();


    Qual tipo de grafico você quer mostrar?

    Qual erro o código apresenta?


    Fulvio C


    terça-feira, 2 de fevereiro de 2016 23:56
  • Boa tarde Willians Fernando,

    Seu código me parece suspeito.

    Por favor, sugiro que olhe o método abaixo e faça as alterações necessárias, visto que esse exemplo é mais robusto e segue as boas práticas de programação.

    public class Data
    
    {
    
        public string ColumnName = "";
    
        public int Value = 0;
    
     
    
        public Data(string columnName, int value)
    
        {
    
            ColumnName = columnName;
    
            Value = value;
    
        }
    
    }    
    
              Here we’ve to create a WebMethod to get the data from server. 
    
        [WebMethod]
    
        public static List<Data> GetData()
    
        {
    
            SqlConnection conn = new SqlConnection("Data Source=SPIDER;Initial                                                                                                    Catalog=Northwind;Integrated Security=True");
    
            DataSet ds = new DataSet();
    
            DataTable dt = new DataTable();
    
            conn.Open();
    
            string cmdstr = "select top 5 Country, COUNT(CompanyName) [Total Suppliers] from                                           [Suppliers] group by Country";
    
            SqlCommand cmd = new SqlCommand(cmdstr, conn);
    
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
    
            adp.Fill(ds);
    
            dt = ds.Tables[0];
    
            List<Data> dataList = new List<Data>();
    
            string cat="";
    
            int val=0;
    
            foreach (DataRow dr in dt.Rows)
    
            {
    
                cat=dr[0].ToString();
    
                val=Convert.ToInt32( dr[1]);
    
                dataList.Add(new Data(cat, val));
    
            }
    
            return dataList;
    
        }
    
             
    
    Here we’ve to use following code to load google JSAPI and JQuery libraries
    
         <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript">      </script>
    
        <script type="text/javascript" src="//www.google.com/jsapi"></script>
    
     
    
    Then we’ve to use following code to load Google visualization and package libraries
    
    <script type="text/javascript">
    
            google.load('visualization', '1', { packages: ['corechart'] });
    
    </script>
    
     
    
    Here I’ll make Ajax call from client to get json object with containing data to be displayed
    
    $(document).ready(function () {
    
                $.ajax({
    
                    type: 'POST',
    
                    dataType: 'json',
    
                    contentType: 'application/json',
    
                    url: 'Default.aspx/GetData',
    
                    data: '{}',
    
                    success:
    
                        function (response) {
    
                            drawVisualization(response.d);
    
                        }
    
                });
    
            })
    
     
    
    Here is the function that can be used to draw the chart
    
    function drawVisualization(dataValues) {
    
                var data = new google.visualization.DataTable();
    
                data.addColumn('string', 'Column Name');
    
                data.addColumn('number', 'Column Value'); 
    
                for (var i = 0; i < dataValues.length; i++) {
    
                    data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
    
                } 
    
                new google.visualization.PieChart(document.getElementById('visualization')).
    
                    draw(data, { title: "Google Chart demo" });
    
            }
    
     
    
    Here we need to create a div tag that would be displayed Google chart
    
    <div id="visualization" style="width: 600px; height: 350px;">
    
    </div>
    
     
    
    Designer source code:
    
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 
    
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <head runat="server">
    
        <title></title>
    
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    
        <script type="text/javascript" src="//www.google.com/jsapi"></script>
    
        <script type="text/javascript">
    
            google.load('visualization', '1', { packages: ['corechart'] });
    
        </script>
    
        <script type="text/javascript">
    
            $(document).ready(function () {
    
                $.ajax({
    
                    type: 'POST',
    
                    dataType: 'json',
    
                    contentType: 'application/json',
    
                    url: 'Default.aspx/GetData',
    
                    data: '{}',
    
                    success:
    
                        function (response) {
    
                            drawVisualization(response.d);
    
                        } 
    
                });
    
            })
    
     
    
            function drawVisualization(dataValues) {
    
                var data = new google.visualization.DataTable();
    
                data.addColumn('string', 'Column Name');
    
                data.addColumn('number', 'Column Value'); 
    
                for (var i = 0; i < dataValues.length; i++) {
    
                    data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
    
                } 
    
                new google.visualization.PieChart(document.getElementById('visualization')).
    
                    draw(data, { title: "Google Chart demo" });
    
            }        
    
        </script>
    
    </head>
    
    <body>
    
        <form id="form1" runat="server">
    
        <div id="visualization" style="width: 600px; height: 350px;">
    
        </div>
    
        </form>
    
    </body>
    
    </html>
    
      
    
    Code Behind:
    
    using System;
    
    using System.Collections.Generic;
    
    using System.Linq;
    
    using System.Web;
    
    using System.Web.UI;
    
    using System.Web.UI.WebControls;
    
    using System.Data;
    
    using System.Data.SqlClient;
    
    using System.Web.Services;
    
    public partial class _Default : System.Web.UI.Page
    
    {
    
        protected void Page_Load(object sender, EventArgs e)
    
        {
    
        }  
    
        [WebMethod]
    
        public static List<Data> GetData()
    
        {
    
            SqlConnection conn = new SqlConnection("Data Source=SPIDER;Initial                                                                                            Catalog=Northwind;Integrated Security=True");
    
            DataSet ds = new DataSet();
    
            DataTable dt = new DataTable();
    
            conn.Open();
    
            string cmdstr = "select top 5 Country, COUNT(CompanyName) [Total Suppliers] from                                           [Suppliers] group by Country";
    
            SqlCommand cmd = new SqlCommand(cmdstr, conn);
    
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
    
            adp.Fill(ds);
    
            dt = ds.Tables[0];
    
            List<Data> dataList = new List<Data>();
    
            string cat="";
    
            int val=0;
    
            foreach (DataRow dr in dt.Rows)
    
            {
    
                cat=dr[0].ToString();
    
                val=Convert.ToInt32( dr[1]);
    
                dataList.Add(new Data(cat, val));
    
            }
    
            return dataList;
    
        }
    
    }
    
    public class Data
    
    {
    
        public string ColumnName = "";
    
        public int Value = 0; 
    
        public Data(string columnName, int value)
    
        {
    
            ColumnName = columnName;
    
            Value = value;
    
        }
    
    }   

    Atenciosamente,




    Roberto Alves

    Por favor, lembre-se de Marcar como Resposta as postagens que resolveram o seu problema. Essa é uma maneira comum de reconhecer aqueles que o ajudaram e fazer com que seja mais fácil para os outros visitantes encontrarem a resolução mais tarde.



    • Editado Roberto AB Filho quarta-feira, 3 de fevereiro de 2016 18:19
    • Marcado como Resposta Marcos SJ quinta-feira, 4 de fevereiro de 2016 15:15
    quarta-feira, 3 de fevereiro de 2016 18:18