C# Add to Y value on chart

2019-09-24 02:29发布

问题:

I am trying to add a List to a chart. This list contains a 2 and a 4.

foreach (decimal D in numbers)
{
    barChart.Series[0].Points.AddXY(1, D);
}

It needs to add D to index 1 on the X axis. However, this only outputs 4 rather than six at X1. When it gets to the 4 in the list, it overwrites the 2 that is there, rather than adding to it (making 6). How do I make it add rather than overwrite?

EDIT: I did not give enough information apparently. I am using Windows Forms. The chart I am using is in the Data section of Visual Studio 2015.

回答1:

You misunderstand the meaning of the AddXY method.

It doesn't change the y- or any values.

AddXY means that a new DataPoint is added to the Points collection.

In your code each will have an x-value of 1 and the y-values of the two points are 2 and 4. To do so you would write, maybe:

barChart.Series[0].Points[0].YValues[0] += D;

If your numbers are decimals you will need to cast to double, which is the base number type for all Chart values:

barChart.Series[0].Points[0].YValues[0] += (double)D;