Thursday 16 February 2012

Pie Chart Exploded Slices

Design Code:


<asp:Chart ID="Chart1" runat="server" Height="340px"
Palette="SemiTransparent" Width="528px">
<Series>
<asp:Series ChartType="Pie"
CustomProperties="PieLineColor=BlanchedAlmond, PieDrawingStyle=SoftEdge"
Legend="Legend1" Name="Series1">
</asp:Series>
</Series>
<ChartAreas>
<asp:ChartArea Name="ChartArea1">
<Area3DStyle Enable3D="True" />
</asp:ChartArea>
</ChartAreas>
<Legends>
<asp:Legend Alignment="Far" Docking="Top" Name="Legend1">
</asp:Legend>
</Legends>
<BorderSkin BackColor="BurlyWood" BackGradientStyle="HorizontalCenter"
BackSecondaryColor="Blue" SkinStyle="Emboss" />
</asp:Chart>

C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.DataVisualization.Charting;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class PieChart : System.Web.UI.Page
{
    SqlConnection con;
    protected void Page_Load(object sender, EventArgs e)
    {
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["CONN"].ConnectionString.ToString());

        // Collection to hold X Axis and Y Axis Values
        Dictionary<string, Decimal> xyValue = new Dictionary<string, Decimal>();

        // Call to chart Data method which return dictionary collection of demo data
        xyValue = chartData();

        // Binding collection key value pair to chart's default series
        Chart1.Series[0].Points.DataBindXY(xyValue.Keys, xyValue.Values);
        Chart1.Series[0].Label = "#VALX (#PERCENT{P0})";

        //=================
        int chartPoints = 0;

        chartPoints = Chart1.Series[0].Points.Count;
        for (int i = 0; i < chartPoints; i++)
        {
            Chart1.Series[0].Points[i].CustomProperties += "Exploded=true";
        }
    }
    public DataTable FetchSale()
    {
        SqlDataAdapter da = new SqlDataAdapter("Select * from SALE", con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }
    protected Dictionary<string, Decimal> chartData()
    {
        // Object to generate random numbers to populate demo data
        //Random rnd = new Random(1);

        DataTable dtsale = FetchSale();

        Dictionary<string, Decimal> values = new Dictionary<string, Decimal>();

        //Populating collection with random values
        for (int i = 0; i < dtsale.Rows.Count; i++)
        {
            values.Add(dtsale.Rows[i][0].ToString(), Convert.ToDecimal(dtsale.Rows[i][1].ToString()));
        }
        return values;
    }
}

Page View:



1 comment:

  1. Can we make each slice of chart clickable. If yes then can you guide me.

    Thanks

    ReplyDelete