Saturday, April 23, 2022

[FIXED] How can I add values from a datagridview into a pie chart in vb.net?

Issue

I would like to represent 2 values from a datagridview into a pie chart. These values are integers and have already been displayed in the datagridview. I just need those values to be displayed in a pie chart. Here is what I've tried:

    For Count As Integer = 0 To DataGridView1.Rows.Count - 2
        Chart1.Series(0).Points.Add(DataGridView1.Item(0, Count).Value, DataGridView1.Item(1, Count).Value)
        Chart1.Series(1).Points.Add(DataGridView1.Item(0, Count).Value, DataGridView1.Item(1, Count).Value)
    Next

This creates a loop to insert all values from the datagridview into the chart. The problem is that when it runs, the chart does not display these two integers.


Solution

  1. Declare the x and y values and the series of the pie chart.

    Dim series As String = "Time"
    Dim yval As Double() = { x, y }
    Dim xval As String() = {"Time Studying", "Time Not Studying"}
    
  2. Retrieve the values from the data grid view.

    For Count As Integer = 0 To DataGridView1.Rows.Count - 2
        x = DataGridView1.Item(0, Count).Value
        y = DataGridView1.Item(1, Count).Value
    Next
    
  3. Clear the graph values

     Chart1.Series.Clear()
     Chart1.Titles.Clear()
    
  4. Plot values into chart.

    Chart1.Series.Add(series)
    Chart1.Series(series).Points.DataBindXY(xval, yval)
    Chart1.Series("Time").IsValueShownAsLabel = True
    Chart1.Series(series).Points(0).Color = Color.LightSkyBlue
    Chart1.Series(series).Points(1).Color = Color.Orange
    Chart1.Series(series).ChartType = SeriesChartType.Pie
    


Answered By - Mario Port
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.