Write a program that allows the user to display a budget as a pie chart. After the user enters numbers into the four text boxes a presses the button, the pie chart should be displayed.
When I push the button for my code it does not display anything. Could you help me determine what I am not doing and give me an idea how to include into my code thanks.
Code below:
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
Dim Housing, Transportation, Food, Other As String
Dim legend() As String = {"Housing", "Transportation", "Food", "Other"}
Dim quantity() As Single = {}
Dim percent(quantity.GetUpperBound(0)) As Single
Dim sumOfQuantities As Single = 0
Dim sumOfSweepAngles As Single = 0
Dim br() As Brush = {Brushes.Blue, Brushes.Red, Brushes.Tan, _
Brushes.Green, Brushes.Orange, Brushes.Gray}
Dim gr As Graphics = picBudget.CreateGraphics
Housing = CStr(txtHousing.Text)
Transportation = CStr(txtTransportation.Text)
Food = CStr(txtFood.Text)
Other = CStr(txtOther.Text)
'The picture box has widith 312 and height 215
Dim r As Integer = 100 'Radius of circle
Dim c As Integer = 105 'Center of circle has coordinates (c,c)
Me.Text = "Budget"
'Convert the quantities to percents
For i As Integer = 0 To quantity.GetUpperBound(0)
percent(i) = quantity(i) / sumOfQuantities
gr.FillPie(br(i), c - r, c - r, 2 * r, 2 * r, sumOfSweepAngles, percent(i) * 360)
sumOfSweepAngles += percent(i) * 360
gr.FillRectangle(br(i), 220, 20 + 30 * i, 20, 20)
gr.DrawString(legend(i), Me.Font, Brushes.Black, 250, 22 + 30 * i)
Next
End Sub
2 answers
1. You will need to declare the dimension of quantity. As it is, I believe it defaults to 1.
You could put in a bunch zeroes to occupy the four spaces, such as:
Dim quantity() As Single = {0, 0, 0, 0}
2. The sum of quantities variable must be calculated using a for-loop prior to drawing the pie-chart which requires "sumOfQuantities" to calculate the percentage. Do not forget to initialize sumOfQuantities to zero before entering the for-loop.
3. You'll need to manually transfer the values of Housing.text into quantity(0), etc. For example:
quantity(0)=CSng(txtHousing.text)
...
After that, the program should work. By changing the values in the textbox, and pressing the button, the graphics will update itself.
Good work!