Generate a Pie Chart at runtime, C#, .NET

We can quickly write a function which returns a Pie Chart at runtime. Assuming that we are making a pie chart for the number of visitors/users from different countries, we will pass System.Data.DataTable as parameter to the function and it shall return a Chart object.

Please add following namespaces to the page/class.

using System.Windows.Forms.DataVisualization.Charting;
using System.Drawing;
using System.Data;

Write the following function to get a Chart as return Parameter. You can pass a Datatable to the funtion with following schema,
Datatable dt (Country Text, Users Int)

Following is the function :

protected internal Chart GetPieChart(DataTable dtChartData)
        {
            Chart pieChart = new Chart()
            {
                Width = 800,
                Height = 800
            };

            ChartArea chartArea1 = new ChartArea();
            Legend legend1 = new Legend() { BackColor = Color.BurlyWood, ForeColor = Color.White, Title = "Countries" };
            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, 100);

            pieChart.Series.Clear();
            pieChart.Palette = ChartColorPalette.Fire;
            pieChart.BackColor = Color.LightYellow;
            pieChart.Titles.Add("User & Country Analytics");
            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);

            int count = 0;
            foreach (DataRow dr in dtChartData.Rows)
            {
                series1.Points.Add(Convert.ToInt32(dr["Users"]));
                var p1 = series1.Points[count];
                p1.AxisLabel = Convert.ToInt32(dr["Users"]).ToString();
                p1.LegendText = Convert.ToString(dr["Country"]);
                count++;
            }
            pieChart.Invalidate();
            return pieChart;
        }

Hope this helps!

Comments

Popular posts from this blog

SharePoint log error "Cannot find site lookup info for request Uri http://"

we're adding your app click here to cancel sharepoint 2013, Unable to install app for SharePoint