Wednesday, November 23, 2016

String was not recognized as a valid DateTime (Assign date value with dd-MM-yyyy format to DateTimePicker control)

Good day!
A question was raised on how to assign a date value with format dd-MM-yyyy (05-11-2016) to a DateTimePicker control Text property. Using Convert.ToDateTime() to assign the given value will cause an exception String was not recognized as a valid DateTime. So, a workaround for this is to parse the date value using DateTime.ParseExact() as presented below. The default format of the DateTimePicker control is long.
var dateObj = DateTime.ParseExact("05-11-2016", "dd-MM-yyyy", CultureInfo.InvariantCulture);
DateAttendancePicker.Text = dateObj.ToString();
Make sure that the second parameter of the function is the correct format of the input value.

0 comments:

Post a Comment