Pie Chart Demo : Chart « Components « C# / C Sharp

C# / C Sharp
1. 2D Graphics
2. Class Interface
3. Collections Data Structure
4. Components
5. Data Types
6. Database ADO.net
7. Design Patterns
8. Development Class
9. Event
10. File Stream
11. Generics
12. GUI Windows Form
13. Language Basics
14. LINQ
15. Network
16. Office
17. Reflection
18. Regular Expressions
19. Security
20. Services Event
21. Thread
22. Web Services
23. Windows
24. XML
25. XML LINQ
Java
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
C# / C Sharp » Components » ChartScreenshots 
Pie Chart Demo
Pie Chart Demo


/*
Code revised from chapter 13


GDI+ Custom Controls with Visual C# 2005
By Iulian Serban, Dragos Brezoi, Tiberiu Radu, Adam Ward 

Language English
Paperback 272 pages [191mm x 235mm]
Release date July 2006
ISBN 1904811604

Sample chapter
http://www.packtpub.com/files/1604_CustomControls_SampleChapter.pdf


For More info on GDI+ Custom Control with Microsoft Visual C# book 
visit website www.packtpub.com 


*/ 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Collections;
using System.Drawing.Printing;

namespace PieChartApp
{
    public partial class Form1 : Form
    {
        Color tempSliceColor;
        string tempSliceName;
        int tempSliceSize;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            pieChart1.AddSlice(new Slice("Mozzarella"55, Color.FromArgb(255128128)));
            pieChart1.AddSlice(new Slice("Gorgonzola"15, Color.FromArgb(128255128)));
            pieChart1.AddSlice(new Slice("Parmigiano"25, Color.FromArgb(128128255)));
            pieChart1.AddSlice(new Slice("Ricotta"25, Color.FromArgb(255128255)));
            // the first unnamed slice will be automatically named "Slice 0"
            pieChart1.AddSlice(new Slice(""25, Color.FromArgb(255255128)));
            // the seconf unnamed slice will be automatically named "Slice 1"
            pieChart1.AddSlice(new Slice(""25, Color.FromArgb(128255255)));
            // get the "Ricotta" slice
            Slice tempSlice = pieChart1.GetSlice("Ricotta");
            // if the slice exists i.e. has the name different form ""
            if (tempSlice.GetSliceName() != "")
                // and name it Ricotta cheese"
                tempSlice.SetSliceName("Ricotta cheese");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            pieChart1.Print(false);
        }

        private void pieChart1_Load(object sender, EventArgs e)
        {

        }

        private void addSliceColorButton_Click(object sender, EventArgs e)
        {
            colorDialog1.ShowDialog();
            tempSliceColor = colorDialog1.Color;
            addSliceColorButton.BackColor = tempSliceColor;

        }

        private void addSliceButton_Click(object sender, EventArgs e)
        {
            if (addSliceNameTextBox.Text.ToString().Length <= 20)
            {
                tempSliceName = addSliceNameTextBox.Text;
            }
            else
            {
                MessageBox.Show("The entered name is not un up to 20 char string");
                return;
            }

            if (ParseNumber(addSliceSizeTextBox.Text))
            {
                if (addSliceSizeTextBox.Text != "")
                    tempSliceSize = Int32.Parse(addSliceSizeTextBox.Text.ToString());
                if (tempSliceSize == 0)
                    return;
            }
            else
            {
                MessageBox.Show("The entered size is not an up to 8 digit number!");
                return;
            }

            if (tempSliceColor.A == 0)
                tempSliceColor = Color.FromArgb(255255255255);
            pieChart1.AddSlice(new Slice(tempSliceName, tempSliceSize, tempSliceColor));
            pieChart1.Invalidate();
            // clean name, size and color
            addSliceNameTextBox.Text = "";
            addSliceSizeTextBox.Text = "";
            tempSliceName = "";
            tempSliceColor = Color.FromArgb(255255255);
            tempSliceSize = 0;
            colorDialog1.Color = Color.FromArgb(255255255255);
            addSliceColorButton.BackColor = Color.FromArgb(236233216);
        }

        private void removeSliceButton_Click(object sender, EventArgs e)
        {
            tempSliceName = removeSliceNameTextBox.Text;
            pieChart1.RemoveSlice(tempSliceName);

        }
        private bool ParseNumber(string userNumber)
        {
            //create our parser that will do all our work for us
            Regex parser = new Regex(@"^\d{0,8}$");
            //return the bool result of parser's findings
            return parser.IsMatch(userNumber);
        }


        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.addSliceButton = new System.Windows.Forms.Button();
            this.addSliceColorButton = new System.Windows.Forms.Button();
            this.label3 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.addSliceSizeTextBox = new System.Windows.Forms.TextBox();
            this.addSliceNameTextBox = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.removeSliceButton = new System.Windows.Forms.Button();
            this.removeSliceNameTextBox = new System.Windows.Forms.TextBox();
            this.label4 = new System.Windows.Forms.Label();
            this.colorDialog1 = new System.Windows.Forms.ColorDialog();
            this.pieChart1 = new PieChartApp.PieChart();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(294383);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(7523);
            this.button1.TabIndex = 1;
            this.button1.Text = "Print";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.addSliceButton);
            this.groupBox1.Controls.Add(this.addSliceColorButton);
            this.groupBox1.Controls.Add(this.label3);
            this.groupBox1.Controls.Add(this.label2);
            this.groupBox1.Controls.Add(this.addSliceSizeTextBox);
            this.groupBox1.Controls.Add(this.addSliceNameTextBox);
            this.groupBox1.Controls.Add(this.label1);
            this.groupBox1.Location = new System.Drawing.Point(51398);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(200139);
            this.groupBox1.TabIndex = 2;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Add Slice";
            // 
            // addSliceButton
            // 
            this.addSliceButton.Location = new System.Drawing.Point(52110);
            this.addSliceButton.Name = "addSliceButton";
            this.addSliceButton.Size = new System.Drawing.Size(7523);
            this.addSliceButton.TabIndex = 6;
            this.addSliceButton.Text = "Add Slice";
            this.addSliceButton.UseVisualStyleBackColor = true;
            this.addSliceButton.Click += new System.EventHandler(this.addSliceButton_Click);
            // 
            // addSliceColorButton
            // 
            this.addSliceColorButton.Location = new System.Drawing.Point(5273);
            this.addSliceColorButton.Name = "addSliceColorButton";
            this.addSliceColorButton.Size = new System.Drawing.Size(7523);
            this.addSliceColorButton.TabIndex = 5;
            this.addSliceColorButton.Text = "Set Color";
            this.addSliceColorButton.UseVisualStyleBackColor = true;
            this.addSliceColorButton.Click += new System.EventHandler(this.addSliceColorButton_Click);
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(773);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(3413);
            this.label3.TabIndex = 4;
            this.label3.Text = "Color:";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(750);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(3013);
            this.label2.TabIndex = 3;
            this.label2.Text = "Size:";
            // 
            // addSliceSizeTextBox
            // 
            this.addSliceSizeTextBox.Location = new System.Drawing.Point(5247);
            this.addSliceSizeTextBox.Name = "addSliceSizeTextBox";
            this.addSliceSizeTextBox.Size = new System.Drawing.Size(10020);
            this.addSliceSizeTextBox.TabIndex = 2;
            // 
            // addSliceNameTextBox
            // 
            this.addSliceNameTextBox.Location = new System.Drawing.Point(5220);
            this.addSliceNameTextBox.Name = "addSliceNameTextBox";
            this.addSliceNameTextBox.Size = new System.Drawing.Size(10020);
            this.addSliceNameTextBox.TabIndex = 1;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(720);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(3813);
            this.label1.TabIndex = 0;
            this.label1.Text = "Name:";
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this.removeSliceButton);
            this.groupBox2.Controls.Add(this.removeSliceNameTextBox);
            this.groupBox2.Controls.Add(this.label4);
            this.groupBox2.Location = new System.Drawing.Point(423398);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(200130);
            this.groupBox2.TabIndex = 3;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Remove Slice";
            // 
            // removeSliceButton
            // 
            this.removeSliceButton.Location = new System.Drawing.Point(3280);
            this.removeSliceButton.Name = "removeSliceButton";
            this.removeSliceButton.Size = new System.Drawing.Size(12423);
            this.removeSliceButton.TabIndex = 2;
            this.removeSliceButton.Text = "Remove Slice";
            this.removeSliceButton.UseVisualStyleBackColor = true;
            this.removeSliceButton.Click += new System.EventHandler(this.removeSliceButton_Click);
            // 
            // removeSliceNameTextBox
            // 
            this.removeSliceNameTextBox.Location = new System.Drawing.Point(5025);
            this.removeSliceNameTextBox.Name = "removeSliceNameTextBox";
            this.removeSliceNameTextBox.Size = new System.Drawing.Size(10020);
            this.removeSliceNameTextBox.TabIndex = 1;
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(628);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(3813);
            this.label4.TabIndex = 0;
            this.label4.Text = "Name:";
            // 
            // pieChart1
            // 
            this.pieChart1.Location = new System.Drawing.Point(3725);
            this.pieChart1.Name = "pieChart1";
            this.pieChart1.SetArray = null;
            this.pieChart1.Size = new System.Drawing.Size(538352);
            this.pieChart1.TabIndex = 0;
            this.pieChart1.Load += new System.EventHandler(this.pieChart1_Load);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(673581);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.pieChart1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private PieChart pieChart1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button addSliceButton;
        private System.Windows.Forms.Button addSliceColorButton;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox addSliceSizeTextBox;
        private System.Windows.Forms.TextBox addSliceNameTextBox;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.Button removeSliceButton;
        private System.Windows.Forms.TextBox removeSliceNameTextBox;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.ColorDialog colorDialog1;



        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
    
   public partial class PieChart : UserControl
    {
        int totalCount;
        ArrayList mySlices;
        PrintDocument pieChartPrintDoc = null;

        public PieChart()
        {
            InitializeComponent();
            pieChartPrintDoc = new PrintDocument();
            pieChartPrintDoc.PrintPage += new PrintPageEventHandler(_pieChartPrintDoc_PrintPage);

        }
        public ArrayList SetArray
        {
            get
            {
                return mySlices;
            }
            set
            {
                if (mySlices != value)
                    mySlices = value;
                Invalidate();
            }
        }
        private void SetValues()
        {
            totalCount = 0;
            if (mySlices != null)
            {
                foreach (Slice slice in mySlices)
                    totalCount += slice.GetSliceRange();
            }
            //mySlicesPercent.Clear();
        }
        public bool AddSlice(Slice slice)
        {
            bool isThisSlice = false;
            if (mySlices == null)
            {
                mySlices = new ArrayList();
                mySlices.Add(slice);
                return true;
            }
            foreach (Slice sliceTemp in mySlices)
            {
                if (sliceTemp.GetSliceName() == slice.GetSliceName())
                    isThisSlice = true;
            }
            if (isThisSlice == false)
            {
                mySlices.Add(slice);
                Invalidate();
                return true;
            }
            return false;
        }

        public bool RemoveSlice(string sliceName)
        {
            bool isThisSliceName = false;
            foreach (Slice sliceTemp in mySlices)
            {
                if (sliceName == sliceTemp.GetSliceName())
                {
                    mySlices.Remove(sliceTemp);
                    isThisSliceName = true;
                    break;
                }
            }
            if (isThisSliceName)
                Invalidate();
            return isThisSliceName;
        }

        private void PieChart_Paint(object sender, PaintEventArgs e)
        {
            {
                Pen penCircle = Pens.Black;
                Pen penLine = Pens.BlanchedAlmond;
                SetValues();
                e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                e.Graphics.DrawEllipse(penCircle, new Rectangle(11this.Width / 5this.Width / 5));
                if (mySlices != null)
                {
                    int actualCount = 0;
                    // draw each slice
                    foreach (Slice slice in mySlices)
                    {
                        Pen penSlice = new Pen(slice.GetSliceColor());
                        int actualRangeSlice = slice.GetSliceRange();
                        int startAngle = (int)((actualCount / (double)totalCount360);
                        int widthAngle = (int)(((actualRangeSlice(double)totalCount3601;
                        Brush br = new SolidBrush(slice.GetSliceColor());
                        e.Graphics.FillPie(br, new Rectangle(11this.Width / 5this.Width / 5), startAngle, widthAngle);
                        e.Graphics.DrawPie(penCircle, new Rectangle(11this.Width / 5this.Width / 5), startAngle, widthAngle);
                        actualCount += slice.GetSliceRange();
                    }
                    // draw the text within the legend
                    string itemName;
                    int itemFontSize = 64;
                    Font itemFont = new Font("SansSerif", itemFontSize);
                    StringFormat itemFormatName = new StringFormat(StringFormatFlags.NoClip);
                    itemFormatName.Alignment = StringAlignment.Near;
                    itemFormatName.LineAlignment = StringAlignment.Near;
                    int verticalPosition = 50;
                    // check if the text fits the legend
                    // if not -> modify the font
                    foreach (Slice slice in mySlices)
                    {
                        itemName = "  ";
                        itemName += slice.GetSliceName();
                        itemName += " - " + string.Format("{0:f}"(double)(slice.GetSliceRange