Search code examples
c#mysqlchartsmariadbpie-chart

How to create a pie chart from my sql database using c#


I am trying to generate a pie chart using a maria mysql database, and I'm currently using for C#. I have searched a few examples but have not found a clear one. Currently my issue is when i run my program it show me only one information (Operations_Dept with 124000 in charttArea)

My table table

my image from my programme

chart

my code

public void LoadChart()
        {
            try
            {
                string allTables = " SELECT sum(Operations_Dept), sum(Operations_Cridet) FROM table_operations";

                MySqlCommand cmd = new MySqlCommand(allTables, ClassConn.MyConnection());
                ClassConn.OpenConnection();
                MySqlDataReader rdr = cmd.ExecuteReader();

                chrt_ventes.Series["columns"].Points.Clear();

                while (rdr.Read())
                {
                    this.chrt_ventes.Series["columns"].Points.AddXY( rdr[0], rdr[1]);

                }
                rdr.Close();
                ClassConn.CloseConnection();
            }

            catch (MySqlException ex) { MessageBox.Show(ex.Message); }
        }

Solution

  • The behavior is totally expected. You have one row and add one data point. I guess you want to add two of them.

    Try

    while (rdr.Read())
    {
         this.chrt_ventes.Series["columns"].Points.AddXY( "Dept" , rdr[0]);
         this.chrt_ventes.Series["columns"].Points.AddXY( "Cred" , rdr[1]);
    }
    

    Mind: This is untested; I have no idea what your charting lib is and how its API works. I just inferred this works from the result you are getting from that code.