How to draw a Pie Chart in Visual Basic.NET

By James J

Shows how to draw pie chart for given different different values & colors

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

'Check values total is 100 or not...
Dim sum = 0
For Each percent In PiePercents
            sum += percent

' If sum not 100 then throw Exception...
If sum <> 100 Then
Throw New ArgumentException("Percentages do not add up to 100.")
End If

' Here it will check that total values & colors value are same or not...
' If not same then throw Exception...
If PiePercents.Length <> PieColors.Length Then
Throw New ArgumentException("There must be the same number of percents and colors.")
End If

Dim PiePercentTotal = 0
For PiePercent = 0 To PiePercents.Length() - 1
            Using brush
As New SolidBrush(PieColors(PiePercent))
FillPie(brush, New Rectangle(Location, PieSize), CSng(PiePercentTotal * 360 / 100), CSng(PiePercents(PiePercent) * 360 / 100))
End Using

            PiePercentTotal += PiePercents(PiePercent)
End Sub

Public Sub DrawPieChartOnForm()
' Here all values total must be 100...
'Here you can increase or decrese value, but must total 100...
Dim PiePercent = {50, 10, 30, 2, 5, 3}
'Write color for each different parts of pie chart...
'Depending on values set the values of color for each different part of pie chart...
Dim PieColors = {Color.Red, Color.Lavender, Color.Blue, Color.Green, Color.Gold, Color.Orange}
        Using PieGraphic =
'Set location of pie chart...
Dim PieLocation As New Point(10, 10)
'Set size of pie chart...
Dim PieSize As New Size(150, 150)
'Call function which create a pie chart of given data...
            DrawPieChart(PiePercent, PieColors, PieGraphic, PieLocation, PieSize)
End Using
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

'call here function, which draw pie chart on the form...
Ebd Sub

How to draw a Pie Chart in Visual Basic.NET  (2546 Views)