Monday, May 12, 2014

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.Dock = System.Windows.Forms.DockStyle.Fill;
            legend1.Name = "Legend1";
            pieChart.Location = new System.Drawing.Point(0, 100);

            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

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

Hope this helps!

No comments:

Visual Studio Build Error - The "GenerateResource" task failed unexpectedly

Error: "The GenerateResource task failed unexpectedly" This error is quite common while building the project in Visual Studio....