Monday, 16 March 2009

Code for creating PieChart in ASP.NET 2.0

GDI+ is great innovation in .NET and it is not limited to desktop applications , you can also use it in pages.Here in example code is used to draw a pie chart in web page using GDI+ Classes of drawings.

Import all Drawings name spaces.

using System.Drawing.Drawing2D;

using System.Drawing;

using System.Drawing.Design;

using System.Drawing.Imaging;

using System.Drawing.Text;

Since to determine the angle of each sector in pie chart we follow following math formula

x°=value of Item A/Total value of all items * 360°

Place a listbox and a button on page. fill listbox with some items

float angletosweep=0;

float totalangle=0;

int _TotalvalueOfAllItems = 0;

for (int index = 0;
index < ListBox1.Items.Count; index++)


_TotalvalueOfAllItems += Convert.ToInt32(ListBox1.Items[index].Text.Trim());


Bitmap _InMemoryBitmap = new Bitmap(200, 200);

Graphics g = Graphics.FromImage(_InMemoryBitmap);

Pen _pen = new Pen(Color.Indigo);

Rectangle _rectangle = new Rectangle(20, 20, 100,

SolidBrush _brush = new



angletosweep = 360 *(Convert.ToInt32(ListBox1.Items[item].Text)) /

g.FillPie(new SolidBrush(ColorCodes(item)), _rectangle, totalangle,

//some code omitted.


_InMemoryBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);




private Color
ColorCodes(int item)


Color[] _colorcodes = new Color[] { Color.Green, Color.Yellow ,
Color.LightCoral, Color.Turquoise , Color.Tomato ,
Color.Tan };

return _colorcodes[item];


call this page from another page and place the url into img tag of calling page.

1 comment:

  1. Can you an example of a 3D piechart.