user3641311
user3641311

Reputation: 185

C# - All objects are getting the same values

I am coding a chart. This is my code:

for (int i = 0; i < 2; i++)
{
    Val= new ChartValues<ObservablePoint>(); // added
    Val.Clear(); // added
    lineSeries = new LineSeries
    {
        Title = "Graph " + i,
        Values = Val,
        Stroke = Brushes.Blue,
        Fill = Brushes.Transparent,
        LineSmoothness = 0,
        PointGeometry = null
    };
    
    for (int jj = 0; jj < 2; jj++)
    {
        Val.Add(new ObservablePoint
        {
            X = jj+i+1,
            Y = jj+i+1
        });
    }
    Col.Add(lineSeries);
}

The problem is that in my Col variable (collection) all series are getting the latest values of the loop, which results are lineSeries are the same. When I use the lineSeries = new LineSeries{}, it should create a new independent object right? Or do I have to erase and create it?

Any help is appreciated.

Upvotes: 0

Views: 125

Answers (2)

Conor
Conor

Reputation: 1088

The issue is that you're reusing the same variable Val to store the actual values. Where is it declared, is it a list? Create a new one each time inside the outer loop and then use it to construct the LineSeries.

for (int i = 0; i < 2; i++)
{
    var Val = new ChartValues<ObservablePoint>();
    for (int jj = 0; jj < 2; jj++)
    {
        Val.Add(new ObservablePoint
        {
            X = jj+i+1,
            Y = jj+i+1
        });
    }
    var lineSeries = new LineSeries
    {
        Title = "Graph " + i,
        Values = Val,
        Stroke = Brushes.Blue,
        Fill = Brushes.Transparent,
        LineSmoothness = 0,
        PointGeometry = null
    };
    
    Col.Add(lineSeries);
}

Upvotes: 5

Serge
Serge

Reputation: 43880

the problem is in line series, you use the same variable, and you are adding the same variable. It it changing each time, and in the end have the last data

lineSeries = new LineSeries
{
       ......
};

should be

var lineSeries = new LineSeries
{
       ......
};

Upvotes: 0

Related Questions