Wednesday, August 24, 2011

WPF - Pie Chart in WPF

In this article i will show you how to Bind Data in Pie chart Control in WPF.


Step 1
First we need to download WPF Toolkit from the following link.
http://wpf.codeplex.com/


Install WPF toolkit on your System.


Step 2
Download Northwind database from the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en

Step 3
Attach a Northwind database into MS-SQL server.



Step 4
Create a WPF Application and give the solution name as WpfPieChart.


Step 5
Adding WPF Toolkit Reference.
To add a reference, right click the References folder of your project in Solution Explorer and select Add Reference.On this dialog, select Browse option and browse the System.Windows.Controls.DataVisualization.Toolkit.dll assembly from the folder where you installed the WPF Toolkit.


DataVisualization.Toolkit.dll Path
C:\Program Files\WPF Toolkit\v3.5.50211.1\System.Windows.Controls.DataVisualization.Toolkit.dll




Click on Image for Better View




Click on Image for Better View


Step 6
Create a Stored Procedure that we fetch count the number of countries in customer table so we can bind these data into Pie Chart Control,it is look like this
CREATE PROCEDURE SpCountCountry
AS
	SELECT Customers.Country,COUNT(Customers.Country) as 'Count' FROM Customers
GROUP BY Customers.Country
ORDER BY Customers.Country ASC  
	
GO 

Step 7
Create a Customers static class in the solution for retrieving number of countries from customer table,it is look like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;     

namespace WpfPieChart
{
    public static class Customers
    {
        /// 
        ///  Count Country in Customers Table
        /// 
        /// 
        public static DataTable GetCustomersData()
        {
            try
            {
                SqlConnection SqlCon = new SqlConnection(@"Data Source=SHREE\SHREE;Initial Catalog=Northwind;Integrated Security=True");
                SqlCon.Open();

                SqlCommand SqlComm = new SqlCommand();
                SqlComm.Connection = SqlCon;
                SqlComm.CommandType = CommandType.StoredProcedure;
                SqlComm.CommandText = "SpCountCountry";

                DataTable Table = new DataTable(); 

                SqlDataAdapter SqlDa = new SqlDataAdapter(SqlComm);
                SqlDa.Fill(Table);

                return Table; 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

    }
}


Step 7
Now Add DataVisualization assemble reference to the page on window tag, it is look like this


xmlns:ChartTools="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"

Finally it's look like this
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ChartTools="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit" 
        x:Class="WpfPieChart.MainWindow" 
        Title="Pie Chart" Height="350" Width="525">

</Window>

Step 8
Now Creates a Pie Chart and Bind customers data in Pie Chart,it's look like this
<Grid>
		<ChartTools:Chart x:Name="PieCustomerChart" Title="Customers Countrywide">
				
			<ChartTools:PieSeries ItemsSource="{Binding}" 
				IndependentValueBinding="{Binding Country}"
				DependentValueBinding="{Binding Count}" Title="{Binding Country}">    	
				</ChartTools:PieSeries> 
			
		</ChartTools:Chart>
	</Grid>

The dependent value is the value displayed on the chart. The independent value is the label shown in the legend. 


Step 9
Now Bind the data in Pie Chart Control in Code Behind,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfPieChart
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            BindPieChart();  // Call BindChart Function in Constructors
        }

        #region Methods
        /// 
        ///  Bind the Pie Chart
        /// 
        private void BindPieChart()
        {
            try
            {
                PieCustomerChart.DataContext = Customers.GetCustomersData();  
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message); 
            }
        }

        #endregion
    }
}

Run the Project.


Output


Click on Image for Better View


Full XAML Code
<Window
		xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
		xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
		xmlns:ChartTools="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit" 
		x:Class="WpfPieChart.MainWindow" 
		Title="Pie Chart" Height="350" Width="525">
	
	<Grid>
		<ChartTools:Chart x:Name="PieCustomerChart" Title="Customers Countrywide">
				
			<ChartTools:PieSeries ItemsSource="{Binding}" 
				IndependentValueBinding="{Binding Country}"
				DependentValueBinding="{Binding Count}" Title="{Binding Country}">    	
				</ChartTools:PieSeries> 
			
		</ChartTools:Chart>
	</Grid>
</Window>

Download
Download Source Code