1

I've got a for loop using a DateTime, I'm trying to add points to a chart by summing the data; however, when running the loop I get this error:

InvalidCastException was unhandled: Invalid cast from 'DateTime' to 'Int32'.

Here is the code in the for loop I am trying:

List<Series> dataSeries = chartDailyCost.Series.ToList();
for (DateTime i = Convert.ToDateTime("00:00"); 
              i <= (Convert.ToDateTime("23:45")); 
              i = i.AddMinutes(15))
{
    double sum = 0d;

    //for every series in the chart collection sum the yvalues at the specified 
    foreach (Series s in dataSeries)
    {
        //This is the line I am getting the error for
        sum += s.Points[Convert.ToInt32(i)].YValues[0];
    }
    DataPoint dp = new DataPoint();
    //Add a new yvalue to the datapoint for the summed series's

    //And I will get an error in this one as well
    dp.XValue = dataSeries[0].Points[Convert.ToInt32(i)].XValue;

    dp.YValues[0] = sum;
    sumSeries.Points.Add(dp);
}
Madison
  • 33
  • 1
  • 7
  • 7
    Let me know what do you expect to be the integer value of "23:45" (as a datetime) – Steve May 07 '15 at 22:36
  • 1
    http://stackoverflow.com/questions/5788883/how-can-i-convert-a-datetime-to-an-int take a look at this. I don't know if it's what you want. – KooKoo May 07 '15 at 22:37
  • The question is, how your Points array is indexed. Is it in 15 minute increments? Then I'd use an int for i with 1 increment for every 15 minutes. Or is it seconds? minutes? hours? There are accessors for all kinds of data inside the DateTime struct. – azt May 07 '15 at 22:42
  • It is in 15 minute increments from 00:00 up to 23:45 – Madison May 07 '15 at 22:44

1 Answers1

1

You never actually need a DateTime, instead what you should do is loop over an int, like so:

const int intervalMinutes = 15;
const int numIntervals = 24 * (60/intervalMinutes);
for(int i = 0; i < numIntervals; ++i)
{
    double sum = 0d;

    //for every series in the chart collection sum the yvalues at the specified 
    foreach (Series s in dataSeries)
    {
        sum += s.Points[i].YValues[0];
    }
    DataPoint dp = new DataPoint();
    //Add a new yvalue to the datapoint for the summed series's

    //And I will get an error in this one as well
    dp.XValue = dataSeries[0].Points[i].XValue;

    dp.YValues[0] = sum;
    sumSeries.Points.Add(dp);
}

If you do need a DateTime inside of your loop, create it like so:

DateTime dateTime = new DateTime().AddMinutes(intervalMinutes * i);
Lukazoid
  • 19,016
  • 3
  • 62
  • 85
  • Hey cheers for that, it does make sense, but when I am searching through each data series for the numintervals, how do I go about that? I missed out the line of code, seen in the first line of the edit, and this: List dataSeries = chartDailyCost.Series.ToList(); cheers for any more help! – Madison May 07 '15 at 23:16