Search This Blog

Saturday, June 11, 2011

Drawing a pie chart in .NET

This program shows how to draw a pie chart from the values obtained from a table..

Imports System.Data.OleDb
Imports System.Drawing.Drawing2D
Imports System.Messaging
Imports System.ServiceProcess

Public Class Form1
Dim Conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mdb1.mdb")
Dim dr As OleDbDataReader
Dim rd As New Random(255)
Dim Arr As New ArrayList
Dim pos As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Bind()
End Sub
Public Sub FinalDrawPieChart()
         Dim APiePercent(Arr.Count) As Integer
         For index = 0 To Arr.Count - 1
          APiePercent(index) = Convert.ToInt32(Arr.Item(index))
         Next
         Using PieGraphic = Me.CreateGraphics()
         DrawPieChart(APiePercent, PieGraphic, New Point(20, 20), New Size(130, 130))
         End Using
     End Sub

     Public Sub DrawPieChart(ByVal PiePercents() As Integer, ByVal PieGraphic As Graphics, ByVal PieLocation As Point, ByVal PieSize As Size)

         Dim sum = 0
         For index = 0 To Arr.Count - 1
         sum += PiePercents(index)
         Next

         Dim eachper As Double
         eachper = 0.0
         For index = 0 To Arr.Count - 1
         eachper = CSng((PiePercents(index) * 100) / sum)
          Next

         Dim PiePercentTotal = 0
         Dim percy As Integer
         percy = 40

         For PiePercent = 0 To Arr.Count - 1
         Using brush As New SolidBrush(Color.FromArgb(rd.Next()))
         PieGraphic.FillPie(brush, New Rectangle(Location, PieSize), CSng((PiePercentTotal * 360) / 100), CSng(((PiePercents(PiePercent) * 100) / sum) * 360) / 100)

         PieGraphic.FillRectangle(brush, 250, percy, 20, 20)
 
         PieGraphic.DrawString(Arr.Item(PiePercent), New Font("Arial", 16), New SolidBrush(Color.Black), New Point(290, percy))

              percy = percy + 30
              End Using

             PiePercentTotal += ((PiePercents(PiePercent) * 100) / sum)
             Next
            Return
            End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Arr.Clear()
         Try
             Conn.Open()
             Dim cmd As OleDbCommand = New OleDbCommand("Select Age From Student", Conn)
             dr = cmd.ExecuteReader
              While dr.Read()
                  Arr.Add(dr.GetValue(0).ToString())
                 pos += 1
              End While
Catch ex As Exception
              MessageBox.Show(ex.ToString())
          Finally
              dr.Close()
             Conn.Close()
         End Try
FinalDrawPieChart()

End Sub

No comments:

Post a Comment