Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

c# - Get data from DataGridView to Chart

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 about them but couldn't find anything that could help me with this specific problem.

Here follows a screenshot of what my DataGridView and my Charts are like, with their respective legends:

DataGridView and Charts

What I need is (at least in theory) a very simple thing. In the "SANITY" chart I need to get the value located at Table[0, 0] into something like sanityChart.Series[0] as its 'Y' value, and so on. Same thing for "UNIT" and "ISSUES DB". Any help will be much appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...