Chart will not display DataPoints

2019-09-12 10:59发布

问题:

I am trying to make a Chart using the values from a dictionary however my Chartdoesn't display anything. My code runs fine with no errors and I have a chart on a form.

I have never made a chart in C# before so I have no clue what I am doing.

This is my code for filling it.

If I remove StatChart.update() it will display the total number of items in the Dictionary on the chart but that is all

    private void FillStatChart(Dictionary<string, int> dictionary)
    {
        int dicLength = dictionary.Count;
        StatChart.Series.Clear();
        StatChart.Series.Add("Occurences");
        foreach (System.Windows.Forms.DataVisualization.Charting.DataPoint point in StatChart.Series["Occurences"].Points)
        {
            foreach (KeyValuePair<string, int> pair in dictionary)
            {
                for (int idx = 0; idx < dicLength; idx++)
                {
                    point.SetValueXY(idx, pair.Value);

                    StatChart.Update();
                }
            }
        }
    }

回答1:

You need to Add the new DataPoints to the Points collection.

Change this:

    foreach (System.Windows.Forms.DataVisualization.Charting.DataPoint point in StatChart.Series["Occurences"].Points)
    {
        foreach (KeyValuePair<string, int> pair in dictionary)
        {
            for (int idx = 0; idx < dicLength; idx++)
            {
                point.SetValueXY(idx, pair.Value);

                StatChart.Update();
            }
        }
    }

to this:

    Series S = StatChart.Series["Occurences"];
    for (int idx = 0; idx < dicLength; idx++)
    {
        KeyValuePair<string, int> pair = dictionary.ElementAt(idx);
        S.Points.AddXY(idx, pair.Value);
        S.Points[idx].ToolTip = pair.Key;  // optional tooltip
    }

SetValueXY is only for changing the values of a DataPoint later.