0

The code

private void DateChanged(CalendarView sender, CalendarViewSelectedDatesChangedEventArgs args)
{
    var myDate = args.AddedDates.First();
    string parsedDate = myDate.ToString();
}

randomly causes this exception

System.InvalidOperationException: 'Sequence contains no elements'

How can I avoid it?

louisfischer
  • 1,968
  • 2
  • 20
  • 38
Samuele Dassatti
  • 259
  • 3
  • 15

4 Answers4

0

This is because you are calling .First() on something which doesn't contain anything/is empty. A better idea would be to call FirstOrDefault() which returns null instead of an exception if you call it on an empty collection.

var myDate = args.AddedDates.FirstOrDefault();
if(myDate != null)
    MyButton.Content = myDate.ToString();
Novastorm
  • 1,439
  • 3
  • 26
  • 40
0

It means that args.AddedDates is NULL or empty. So to avoid this error, you'll need to check if it's not null or empty.

private void DateChanged(CalendarView sender, CalendarViewSelectedDatesChangedEventArgs args)
{
    if (args.AddedDates != null && args.AddedDates.Count > 0)
    {
        var myDate = args.AddedDates.First();
        string parsedDate = myDate.ToString();
    }
}
Michael Coxon
  • 5,311
  • 1
  • 24
  • 51
Stef Geysels
  • 1,023
  • 11
  • 27
0

There is a couple things you can do here...

First you can allow for an empty collection..

private void DateChanged(CalendarView sender, CalendarViewSelectedDatesChangedEventArgs args)
{
    var myDate = args.AddedDates.FirstOrDefault();
    if (myDate != null)
    {
        string parsedDate = myDate.ToString();
    }
}

Secondly you could check the collection beforehand...

private void DateChanged(CalendarView sender, CalendarViewSelectedDatesChangedEventArgs args)
{
    if(args.AddedDates != null || args.AddedDates.Any())
    {
        var myDate = args.AddedDates.First();
        string parsedDate = myDate.ToString();
    }
}

Some simple debugging would have told you that the issue is probably in the AddedDates property.

Michael Coxon
  • 5,311
  • 1
  • 24
  • 51
0

Similar to other answers, but args could also be null so I would use:

if (args?.AddedDates != null && args.AddedDates.Any())
{
    var myDate = args.AddedDates.First();
    string parsedDate = myDate.ToString();
}

EDIT:

As has been pointed out, the above only works in C# 6.0 or higher. An alternative that will work in all versions is:

if (args != null && args.AddedDates != null && args.AddedDates.Any())
{
    var myDate = args.AddedDates.First();
    string parsedDate = myDate.ToString();
}
swatsonpicken
  • 873
  • 1
  • 7
  • 21