Pie Chart In ASP.Net

Background

Sometimes we need to show data in a chart like a Pie chart, such as to show quarterly data and on, so by considering the preceding requirement and to introduce the ASP.Net Pie Chart controls I have decided to write this article.

Let us learn about the ASP.Net chart type Pie chart that provides a powerful UI and design quality. We will learn about these chart type controls step-by-step. All the charts are in the System.Web.UI.DataVisualization.Charting namespace.
 
Chart data is represented using the following points:
  1. X Axis: the horizontal line of the chart termed the X axis
  2. Y Axis: the vertical line of the chart termed the Y axis

Now let us learn about the properties of the Pie chart. A Pie chart type has the following common properties:

  • AlternetText: Sets the alternate text when the image is not available
  • Annotation: Stores the chart annotations
  • AntiAliasing: sets a value that determines whether anti-aliasing is used when text and graphics are drawn
  • BackGradientStyle: sets the orientation for the background gradient for the Chart control. Also determines whether a gradient is used, the default is None
  • Backcolor: sets the background color for a chart, the default color is White
  • BackImage: sets the background image for the chart control.
  • BackHatchStyle: sets the hatching style for the chart control, the default is None.
  • Height: Sets the height for the chart control
  • Width: Sets the width for the chart control
  • Palette: Sets the style with the color for the chart control, the default style is Chocolate.
  • PaletteCustomColors: Sets the custom color for the chart control.
  • Series: Sets the series collection for the chart control
  • Legends: Sets the series of legends to the chart

Now let us show the preceding explanation with a practical example by creating a simple web application.

Step 1: Create the table for the chart data
 
Now before creating the application, let us create a table named QuarterwiseSale in a database from where we show the records in the chart using the following script:
  1. CREATE TABLE [dbo].[QuarterwiseSale](  
  2.     [id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Quarter] [varchar](50) NULL,  
  4.     [SalesValue] [money] NULL,  
  5.  CONSTRAINT [PK_QuarterwiseSale] PRIMARY KEY CLUSTERED   
  6. (  
  7.     [id] ASC  
  8. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  9. ON [PRIMARY]
The table has the following fields (shown in the following image):  
 
 
Now insert some records using the following script:
  1. SET IDENTITY_INSERT [dbo].[QuarterwiseSale] ON   
  2.   
  3. GO  
  4. INSERT [dbo].[QuarterwiseSale] ([id], [Quarter], [SalesValue]) VALUES (1, N'Q1', 100.0000)  
  5. GO  
  6. INSERT [dbo].[QuarterwiseSale] ([id], [Quarter], [SalesValue]) VALUES (2, N'Q2', 50.0000)  
  7. GO  
  8. INSERT [dbo].[QuarterwiseSale] ([id], [Quarter], [SalesValue]) VALUES (3, N'Q3', 150.0000)  
  9. GO  
  10. INSERT [dbo].[QuarterwiseSale] ([id], [Quarter], [SalesValue]) VALUES (4, N'Q4', 200.0000)  
  11. GO  
  12. SET IDENTITY_INSERT [dbo].[QuarterwiseSale] OFF  
  13. GO 
Now the records will look as in the list in the following image:
 
 
Now create the Stored Procedure to fetch the records from database as in the following:
  1. Create Procedure [dbo].[GetSaleData]  
  2. (  
  3. @id int=null  
  4.   
  5.   
  6. )  
  7. as  
  8. begin  
  9. Select Quarter,SalesValue from QuarterwiseSale  
  10. End 
I hope you have the same type of table and records as above.
 
Step: 2 Create Web Application

Now create the project using the following:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".

  2. "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).

  3. Provide the project a name such as UsingPieChart or another as you wish and specify the location.

  4. Then right-click on Solution Explorer and select "Add New Item" then select Default.aspx page.

  5. Drag and Drop a Chart control from the ToolBox onto the Default.aspx page.
Now the Default.aspx source code will be as follows:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  
  4.     Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>  
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  6. <html xmlns="http://www.w3.org/1999/xhtml">  
  7. <head runat="server">  
  8.     <title>Article by Vithal Wadje</title>  
  9. </head>  
  10. <body bgcolor="Navy">  
  11.     <form id="form1" runat="server">  
  12.     <h4 style="color: White;">  
  13.         Article for C#Corner  
  14.     </h4>  
  15.     <asp:Chart ID="Chart1" runat="server" BackColor="0, 0, 64" BackGradientStyle="LeftRight"  
  16.         BorderlineWidth="0" Height="360px" Palette="None" PaletteCustomColors="Maroon"  
  17.         Width="380px" BorderlineColor="64, 0, 64">  
  18.         <Titles>  
  19.             <asp:Title ShadowOffset="10" Name="Items" />  
  20.         </Titles>  
  21.         <Legends>  
  22.             <asp:Legend Alignment="Center" Docking="Bottom" IsTextAutoFit="False" Name="Default"  
  23.                 LegendStyle="Row" />  
  24.         </Legends>  
  25.         <Series>  
  26.             <asp:Series Name="Default" />  
  27.         </Series>  
  28.         <ChartAreas>  
  29.             <asp:ChartArea Name="ChartArea1" BorderWidth="0" />  
  30.         </ChartAreas>  
  31.     </asp:Chart>  
  32.     </form>  
  33. </body>  
  34. </html> 
Create a method to bind the chart control. Then open the default.aspx.cs page and create the following function named Bindchart to bind the Chart Control as in the following:
  1. private void Bindchart()  
  2. {  
  3.     connection();  
  4.     com = new SqlCommand("GetSaleData", con);  
  5.     com.CommandType = CommandType.StoredProcedure;  
  6.     SqlDataAdapter da = new SqlDataAdapter(com);  
  7.     DataSet ds = new DataSet();  
  8.     da.Fill(ds);  
  9.   
  10.     DataTable ChartData = ds.Tables[0];  
  11.   
  12.     //storing total rows count to loop on each Record  
  13.     string[] XPointMember = new string[ChartData.Rows.Count];  
  14.     int[] YPointMember = new int[ChartData.Rows.Count];  
  15.   
  16.     for (int count = 0; count < ChartData.Rows.Count; count++)  
  17.     {  
  18.         //storing Values for X axis  
  19.         XPointMember[count] = ChartData.Rows[count]["Quarter"].ToString();  
  20.         //storing values for Y Axis  
  21.         YPointMember[count] = Convert.ToInt32(ChartData.Rows[count]["SalesValue"]);  
  22.   
  23.     }  
  24.     //binding chart control  
  25.     Chart1.Series[0].Points.DataBindXY(XPointMember, YPointMember);  
  26.   
  27.     //Setting width of line  
  28.     Chart1.Series[0].BorderWidth = 10;  
  29.     //setting Chart type   
  30.     Chart1.Series[0].ChartType = SeriesChartType.Pie;  
  31.     foreach (Series charts in Chart1.Series)  
  32.     {  
  33.         foreach (DataPoint point in charts.Points)  
  34.         {  
  35.             switch (point.AxisLabel)  
  36.             {  
  37.                 case "Q1": point.Color = Color.RoyalBlue; break;  
  38.                 case "Q2": point.Color = Color.SaddleBrown; break;  
  39.                 case "Q3": point.Color = Color.SpringGreen; break;  
  40.             }  
  41.             point.Label = string.Format("{0:0} - {1}", point.YValues[0], point.AxisLabel);  
  42.   
  43.         }  
  44.    }
  45.    //Enabled 3D  
  46.    //  Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;  
  47.    con.Close();  
  48.   

 Note that we have written a small code snippet to give the different color for each point as in the following:

  1. //To give different color for each point  
  2.   
  3. foreach (Series charts in Chart1.Series)    
  4. {    
  5.     foreach (DataPoint point in charts.Points)    
  6.     {    
  7.         switch (point.AxisLabel)    
  8.         {    
  9.             case "Q1": point.Color = Color.RoyalBlue; break;    
  10.             case "Q2": point.Color = Color.SaddleBrown; break;    
  11.             case "Q3": point.Color = Color.SpringGreen; break;    
  12.         }    
  13.         point.Label = string.Format("{0:0} - {1}", point.YValues[0], point.AxisLabel);    
  14.    
  15.     }    
  16. }     
 Now, call the preceding function on page load as in the following:
  1. protected void Page_Load(object sender, EventArgs e)    
  2. {    
  3.     if (!IsPostBack)    
  4.     {    
  5.         Bindchart();    
  6.     
  7.     }    
  8. }   
The entire code of the default.aspx.cs page will look as follows:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data.SqlClient;  
  8. using System.Configuration;  
  9. using System.Data;  
  10. using System.Web.UI.DataVisualization.Charting;  
  11. using System.Drawing;  
  12.   
  13. public partial class _Default : System.Web.UI.Page  
  14. {  
  15.     private SqlConnection con;  
  16.     private SqlCommand com;  
  17.     private string constr, query;  
  18.     private void connection()  
  19.     {  
  20.         constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();  
  21.         con = new SqlConnection(constr);  
  22.         con.Open();  
  23.   
  24.     }  
  25.     protected void Page_Load(object sender, EventArgs e)  
  26.     {  
  27.         if (!IsPostBack)  
  28.         {  
  29.             Bindchart();  
  30.   
  31.         }  
  32.     }  
  33.     private void Bindchart()  
  34.     {  
  35.         connection();  
  36.         com = new SqlCommand("GetSaleData", con);  
  37.         com.CommandType = CommandType.StoredProcedure;  
  38.         SqlDataAdapter da = new SqlDataAdapter(com);  
  39.         DataSet ds = new DataSet();  
  40.         da.Fill(ds);  
  41.   
  42.         DataTable ChartData = ds.Tables[0];  
  43.   
  44.         //storing total rows count to loop on each Record  
  45.         string[] XPointMember = new string[ChartData.Rows.Count];  
  46.         int[] YPointMember = new int[ChartData.Rows.Count];  
  47.   
  48.         for (int count = 0; count < ChartData.Rows.Count; count++)  
  49.         {  
  50.             //storing Values for X axis  
  51.             XPointMember[count] = ChartData.Rows[count]["Quarter"].ToString();  
  52.             //storing values for Y Axis  
  53.             YPointMember[count] = Convert.ToInt32(ChartData.Rows[count]["SalesValue"]);  
  54.   
  55.         }  
  56.         //binding chart control  
  57.         Chart1.Series[0].Points.DataBindXY(XPointMember, YPointMember);  
  58.   
  59.         //Setting width of line  
  60.         Chart1.Series[0].BorderWidth = 10;  
  61.         //setting Chart type   
  62.         Chart1.Series[0].ChartType = SeriesChartType.Pie;  
  63.   
  64.   
  65.         foreach (Series charts in Chart1.Series)  
  66.         {  
  67.             foreach (DataPoint point in charts.Points)  
  68.             {  
  69.                 switch (point.AxisLabel)  
  70.                 {  
  71.                     case "Q1": point.Color = Color.RoyalBlue; break;  
  72.                     case "Q2": point.Color = Color.SaddleBrown; break;  
  73.                     case "Q3": point.Color = Color.SpringGreen; break;  
  74.                 }  
  75.                 point.Label = string.Format("{0:0} - {1}", point.YValues[0], point.AxisLabel);  
  76.   
  77.             }  
  78.         }
  79.         //Enabled 3D  
  80.       //  Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;  
  81.         con.Close();  
  82.   
  83.     }  

We now have the entire logic to bind the chart from the database, let us run the application. The chart will look as follows:
 
Now let us change the Point color as:
  1. foreach (Series charts in Chart1.Series)  
  2. {  
  3.     foreach (DataPoint point in charts.Points)  
  4.     {  
  5.         switch (point.AxisLabel)  
  6.         {  
  7.             case "Q1": point.Color = Color.YellowGreen; break;  
  8.             case "Q2": point.Color = Color.Yellow; break;  
  9.             case "Q3": point.Color = Color.SpringGreen; break;  
  10.         }  
  11.         point.Label = string.Format("{0:0} - {1}", point.YValues[0], point.AxisLabel);  
  12.   
  13.     }  
  14. }   
Now the chart will look as follows:
 
 
In the preceding chart we saw how the data is properly arranged with the user interactive graphics, now let us set the 3D style enabled as in the following:
  1. Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;   
 Now the chart will look as follows:
 
 
Now change the Border width as: 
  1. //Setting width of line        
  2.  Chart1.Series[0].BorderWidth = 4;     
Now the chart will look as follows:
 

Now from all the preceding explanations we saw how to create and use a Pie type chart.

Notes
  • Download the Zip file from the attachment for the full source code of the application.
  • Change the connection string in the web.config file to specify your server location.
Summary
 
My next article explains another chart type of ASP.Net. I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.


Similar Articles