Xamarin How to store a date from a Date Picker

Issue

I am using a DatePicker in Xamarin, but am confused how to store the selected date to a variable whenever a new date is selected in the DatePicker.

This is my current code:

private void DateSelected(object sender, DateTime e)
        {
            DateTime date  (DateTime)e;
            Debug.WriteLine(date);
        }

But the date keeps defaulting to 1/1/0001

Solution

Your event handler isn’t quite right. e is not a DateTime but a DateChangedEventArgs, which contains the DateTime selected. Your code should be:

private void DatePicker_DateSelected(object sender, DateChangedEventArgs e)
{
    DateTime newDate  e.NewDate;
}

Answered By – Robot Head

Leave a Comment