Get data from DataGridView to Chart

前端 未结 1 1865
醉梦人生
醉梦人生 2020-12-21 14:40

I need to get data from a single DataGridView into 3 distinct Charts, each column to a chart. This is the first time I\'m working with charts, so I\'ve researched a bit abou

相关标签:
1条回答
  • 2020-12-21 15:18

    From the way you asked the question and the image you have shown I believe that you want something like this:

    enter image description here

    I use only one Chart and I have added one Series for each of your Columns.

    After setting up the chart I have added one data point for each row in the table to each of the series/columns..:

    // setting up the datagridview
    Table.Rows.Clear();
    Table.Columns.Clear();
    Table.Columns.Add("state", "");
    Table.Columns.Add("sanity", "SANITY");
    Table.Columns.Add("unit", "UNIT");
    Table.Columns.Add("issuesDb", "ISSUES DB");
    // filling in some data
    Table.Rows.Add("ALL PASSED", 86, 21, 2);
    Table.Rows.Add("FAILED", 7, 0, 1);
    Table.Rows.Add("Cancelled", 0, 0, 0);
    
    // Now we can set up the Chart:
    List<Color> colors = new List<Color>{Color.Green, Color.Red, Color.Black};
    
    chart1.Series.Clear();
    
    for (int i = 0 ; i < Table.Rows.Count; i++)
    {
        Series S = chart1.Series.Add(Table[0, i].Value.ToString());
        S.ChartType = SeriesChartType.Column;
        S.Color = colors[i];
    }
    
    // and fill in all the values from the dgv to the chart:
    for (int i = 0 ; i < Table.Rows.Count; i++)
    {
       for (int j = 1 ; j < Table.Columns.Count; j++)
       {
          int p = chart1.Series[i].Points.AddXY(Table.Columns[j].HeaderText, Table[j, i].Value);
       }
    }
    

    Note that I have chosen to add the DataPoints with the AddXY overload and also decided that I want to make my life a little easier by adding the X-Values as strings. Internally they are still transformed to doubles and will all have a value of 0! Not a problem for us here, but it is important to understand that we didn't use valid numbers and therefore can't treat them as numbers! The advantage is that the axis labels are being set to the column headers without any further work..

    0 讨论(0)
提交回复
热议问题