Click here to Skip to main content
15,068,678 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have set my form up with a DateTimePicker with the format of #dd MMMM yyyy dddd tt#
When the date and time have been selected the data is stored in an xml file for example as

"22 April 2021 Thursday 10.01 PM"
However, when I try and retrieve the data to populate the DateTimePicker box I get this error

System.FormatException: 'String was not recognized as a valid DateTime.'

If I truncate the data in the xml file to "22 April 2021" the code runs and "22 April 2021 Thursday 12.00 AM" is displayed in the DateTimePicker box.
I have included a subroutine
Public Sub SetMyCustomFormat()
        ' Set the Format type and the CustomFormat string.
        DatePicker.Format = DateTimePickerFormat.Custom
        DatePicker.CustomFormat = "dd MMMM yyyy dddd tt"
    End Sub 'SetMyCustomFormat for dates

Line of code that causes the problem is
DatePicker.Text = node.SelectSingleNode("DatePicker", nsmgr).InnerText

It seems the format expected is "dd MMMM yyyy"

Anybody got any ideas?

What I have tried:

Searched the internet but no answers found.
Updated 22-Apr-21 22:00pm

1 solution

The main problem is that you are trying to set DateTimePicekr's Text property instead of Value.
Dim nodeText As String =  "22 April 2021 Thursday 10.01 PM" 'node.SelectSingleNode("DatePicker", nsmgr).InnerText
Dim myDate As DateTime = DateTime.ParseExact(nodeText, "dd MMMM yyyy dddd tt", System.Globalization.CultureInfo.InvariantCulture)
DatePicker.Value = myDate

For further details, please read:
Set and Return Dates with DateTimePicker Control - Windows Forms .NET Framework | Microsoft Docs[^]
DateTimePicker.Value Property (System.Windows.Forms) | Microsoft Docs[^]
DateTime.ParseExact Method (System) | Microsoft Docs[^]
Dave the Golfer 23-Apr-21 4:54am
Maciej Los Thanks for your solution. All is now working. Wrote the original program some 4 years ago. Have not used since then and even then I taught myself using the internet as a hobby since retiring.
Maciej Los 23-Apr-21 5:05am
You're very welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900