Sunday, November 17, 2013

Creating PIE chart using Microsoft Chart Controls in ASP.NET

In this article i will be creating PIE chart using Microsoft Chart Controls available with .NET Framework 4.0.

I will display a companies advisor's commission details as PIE chart on the web page.

Lets start with the designing:

Select ToolBox -> Data -> Chart option

You can drag and drop the chart control in your web page or double click the chart control option and it will be added to the web page.

Aspx Code:-
1. asp:Series
   Label="#PERCENT" (property value is required if you want to display the result in percentile format)
2. asp:ChartArea 
   Area3DStyle-Inclination="10" (property value is required if you want control the chart inclination. Max value allowed is 90)  
<asp:Chart ID="PieChart" runat="server" Height="250px" Width="500px">
   <asp:Series Name="ChartSeries" ChartType="Pie" ChartArea="MainArea" IsValueShownAsLabel="true" Label="#PERCENT" >
  <asp:ChartArea Name="MainArea" Area3DStyle-Inclination="10" Area3DStyle-IsClustered="false" Area3DStyle-Enable3D="true" >

Code behind (.cs file):-

void createChart()
//creating a DataTable object
DataTable oDataTable = new DataTable();
//Adding columns to the datatable
oDataTable.Columns.Add("Advisor_Name", typeof(String));
oDataTable.Columns.Add("Color", typeof(String));
oDataTable.Columns.Add("Commission", typeof(Double));

//Adding new Row to the table
DataRow dr = oDataTable.NewRow();

//Adding advisor details as rows
dr["Advisor_Name"] = "Stephen Smith";
dr["Color"] = "Green";
dr["Commission"] = 6000.50;

dr = oDataTable.NewRow();
dr["Advisor_Name"] = "Reggie Augstin";
dr["Color"] = "Red";
dr["Commission"] = 20000.90;

dr = oDataTable.NewRow();
dr["Advisor_Name"] = "Rahul Mehta";
dr["Color"] = "Blue";
dr["Commission"] = 35000;

foreach (DataRow dr in oDataTable.Rows)
  DataPoint oDataPoint = new DataPoint(0, double.Parse(dr["Commission"].ToString()));
  oDataPoint.Color = System.Drawing.Color.FromName(dr["Color"].ToString());
  //adding tooltip
  oDataPoint.ToolTip = dr["Advisor_Name"].ToString()+" Earned "+ dr["Commission"].ToString()+" as Commission";

PieChart.Series["ChartSeries"]["PointWidth"] = "0.1";
PieChart.Series["ChartSeries"]["DrawingStyle"] = "Cylinder";
PieChart.Series["ChartSeries"]["PieLabelStyle"] = "Outside";
PieChart.Series["ChartSeries"].Font = new System.Drawing.Font("Calibri", 7, System.Drawing.FontStyle.Regular);

PieChart.ChartAreas["MainArea"].InnerPlotPosition.Width = 40;
PieChart.ChartAreas["MainArea"].InnerPlotPosition.Height = 98;
PieChart.ChartAreas["MainArea"].InnerPlotPosition.X = 25;
PieChart.ChartAreas["MainArea"].InnerPlotPosition.Y = 1;


Hope this helps.

Happy Coding.....

No comments :

Post a Comment