Having problems with date and time editing

Here is my code:

private void textBox1_TextChanged(object sender, EventArgs e)
{
     DateTime myDate = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd H:m:s",
     System.Globalization.CultureInfo.InvariantCulture);

     TimeChangedHandler(myDate);
} 

If I delete 1 number from hours then it works fine, but if I delete both numbers e.x. I want to change from 11 to 22 then it crashes. So how do I make the form "yyyy-MM-dd H:m:s" work for all cases? Thanks!

Jon Skeet
people
quotationmark

If you want to indicate that the date/time is invalid, use DateTime.TryParseExact to check whether or not it's valid, without throwing an exception. Use the return value (true/false) to determine the validity.

Basically, you shouldn't expect that the value is always valid while the user is editing - just like while I'm editing code, it won't always be syntactically correct.

You need to check that it's valid when you actually use the value - and until then, probably just add a visual marker to indicate that it's invalid.

You may want to think about whether your TimeChangedHandler (whatever that is) should implicitly fire whenever the date/time provided is valid, or whether your UI should provide a more explicit "use this value" action (e.g. a button).

Also, consider using a DateTimePicker as a friendlier way of selecting a date and time.

Finally, I'd personally avoid using a pattern of H:m:s... the date part looks like ISO-8601-like, so I'd suggest using HH:mm:ss for complete validity - it would be odd (IMO) to see a value of 2015-07-27 7:55:5 for example.

people

See more on this question at Stackoverflow