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,621
  • 1
  • 18
  • 35

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,298
  • 3
  • 22
  • 39
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
  • 4,806
  • 1
  • 21
  • 49
Stef Geysels
  • 957
  • 10
  • 23
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
  • 4,806
  • 1
  • 21
  • 49
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
  • 631
  • 1
  • 4
  • 18