Thursday, June 21, 2012

Dynamically Creating Pie/Bar Chart in C# WinForms

Chart control is available in Data Category of ToolBox in Windows Form Application.

If not available then

First Download Microsoft Chart Controls for Microsoft .NET Framework 3.5  and install it. 



After that, right click on ToolBox, select Choose Items and then select namespaces checked in above image.

now Chart control is added into your toolbox.


Add Reference System.Windows.Forms.DataVisualization
Create Chart

Step 1 : Add New Windows Form in your Application.


Add Two panels in your Form, one for Pie chart and one for Bar chart as in shown below image.




Step 2 : Go to Code Behind (C#) and initialize chart controls.

public partial class Form1 : Form
    {
        Chart pieChart;
        Chart barChart;
        public Form1()
        {
            InitializeComponent();
            InitializeChart();
        }
        private void InitializeChart()
        {

            this.components = new System.ComponentModel.Container();
            ChartArea chartArea1 = new ChartArea();
            Legend legend1 = new Legend() 
              { BackColor = Color.Green, ForeColor = Color.Black, Title = "Salary" };
            Legend legend2 = new Legend() 
              { BackColor = Color.Green, ForeColor = Color.Black, Title = "Salary" };
            pieChart = new Chart();
            barChart = new Chart();

            ((ISupportInitialize)(pieChart)).BeginInit();
            ((ISupportInitialize)(barChart)).BeginInit();

            SuspendLayout();

            //===Pie chart
            chartArea1.Name = "PieChartArea";
            pieChart.ChartAreas.Add(chartArea1);
            pieChart.Dock = System.Windows.Forms.DockStyle.Fill;
            legend1.Name = "Legend1";
            pieChart.Legends.Add(legend1);
            pieChart.Location = new System.Drawing.Point(0, 50);

            //====Bar Chart
            chartArea1 = new ChartArea();
            chartArea1.Name = "BarChartArea";
            barChart.ChartAreas.Add(chartArea1);
            barChart.Dock = System.Windows.Forms.DockStyle.Fill;
            legend2.Name = "Legend3";
            barChart.Legends.Add(legend2);

            AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            //this.ClientSize = new System.Drawing.Size(284, 262);           
            this.Load += new EventHandler(Form1_Load);
            ((ISupportInitialize)(this.pieChart)).EndInit();
            ((ISupportInitialize)(this.barChart)).EndInit();
            this.ResumeLayout(false);

        }

        void Form1_Load(object sender, EventArgs e)
        {
            LoadPieChart();
            LoadBarChart();
        }
} 

Step 3 : Create Methods to Create Pie and Bar charts and load into Panels.
 
        void LoadPieChart()
        {
            pieChart.Series.Clear();
            pieChart.Palette = ChartColorPalette.Fire;
            pieChart.BackColor = Color.LightYellow;
            pieChart.Titles.Add("Employee Salary");
            pieChart.ChartAreas[0].BackColor = Color.Transparent;
            Series series1 = new Series
            {
                Name = "series1",
                IsVisibleInLegend = true,
                Color = System.Drawing.Color.Green,
                ChartType = SeriesChartType.Pie
            };
            pieChart.Series.Add(series1);
            series1.Points.Add(70000);
            series1.Points.Add(30000);
            var p1 = series1.Points[0];
            p1.AxisLabel = "70000";
            p1.LegendText = "Hiren Khirsaria";
            var p2 = series1.Points[1];
            p2.AxisLabel = "30000";
            p2.LegendText = "ABC XYZ";
            pieChart.Invalidate();
            pnlPie.Controls.Add(pieChart);
        }
        void LoadBarChart()
        {
            barChart.Series.Clear();
            barChart.BackColor = Color.LightYellow;           
            barChart.Palette = ChartColorPalette.Fire;
            barChart.ChartAreas[0].BackColor = Color.Transparent;
            barChart.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            barChart.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
            Series series = new Series
            {
                Name = "series2",
                IsVisibleInLegend = false,
                ChartType = SeriesChartType.Column
            };
            barChart.Series.Add(series);
            series.Points.Add(70000);
            var p1 = series.Points[0];
            p1.Color = Color.Red;
            p1.AxisLabel = "Hiren Khirsaria";
            p1.LegendText = "Hiren Khirsaria";
            p1.Label = "70000";
           
            series.Points.Add(30000);
            var p2 = series.Points[1];
            p2.Color = Color.Yellow;
            p2.AxisLabel = "ABC XYZ";
            p2.LegendText = "ABC XYZ";
            p2.Label = "30000";
            barChart.Invalidate();
            
            pnlBar.Controls.Add(barChart);
        }


Above methods create Pie chart and Bar chart, that display employee salary.

Below image shows final result ( showing Pie and Bar charts)


23 comments:

  1. Firstly, thanks for doing this. I am finding it helpful as I am a novice.

    What is the point of legend2.Name = "Legend3"? Also, where is the legend on the bar chart?

    ReplyDelete
    Replies
    1. 1. What is the point of legend2.Name = "Legend3"?
      ANSWER : legend2.Name = "Legend3" is just name of the legend, you can give any name like unique identifier.

      2. where is the legend on the bar chart?
      ANSWER : I think you have not fully read my article, in LoadBarChart() please check this line : IsVisibleInLegend = false
      I set legend visibility to hide.

      Delete
  2. Hello Hiren Khirsaria,
    ur code was helpful and can u help me in how to draw chat dynamically in report viewer (RDLC)

    ReplyDelete
  3. can we use this to add chart into rdlc report

    ReplyDelete
  4. thanks for "pieChart.Invalidate();" code

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. 1) Can you also explain what is the function of legend class in c#?
    2) Please explain what is the function of p1.legendtext and p2.legendtext in your code? because i have tried changing them but the code hasnt changed it didnt effect the code.

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. how to create dynamically pie chart so that it retrieve value directly from database.

    ReplyDelete
  10. I LOVE U MAN, the unique code functional is this

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. For Bar chart, even if I enable IsVisibleInLegend to true , it is not showing, only it is displaying series instead of legends. help me to fix this.

    ReplyDelete
  13. Thank you for putting this demo together!

    I am having a problem, though. I am using VS2015 Community. The program cannot compile on the lines

    pnlPie.Controls.Add(pieChart);
    pnlBar.Controls.Add(barChart);

    The error messages I get are:
    "CS0103: The name 'pnlPie' does not exist in the current context." and
    "CS0103: The name 'pnlBar' does not exist in the current context."

    I don't see pnlPie or pnlBar mentioned anywhere else on the page. Where are they supposed to be defined?

    ReplyDelete
  14. Never mind, I figured it out.

    For anyone else having this problem: In the Form1.cs (Design) view, I clicked on one form, went over to Properties pane, clicked in Design/Name, and changed the name to pnlBar. Clicked the other form and renamed it as pnlPie. Everything displays like a charm.

    Thank you again so much!!!

    ReplyDelete
  15. You can replace this sentence "pnlPie.Controls.Add(pieChart);"

    by "pieChart.Legends.Add("");"

    ReplyDelete
  16. Thank you very much, this was very helpful.

    ReplyDelete
  17. Thank you for this sample code.. 3 thumbs up!!! :)

    ReplyDelete