I doubt I am the only one who has come up with this solution, but if you have a better one please post it here. I simply want to leave this question here so I and others can search it later.
I needed to tell whether a valid date had been entered into a text box and this is the code that I came up with. I fire this when focus leaves the text box.
try
{
DateTime.Parse(startDateTextBox.Text);
}
catch
{
startDateTextBox.Text = DateTime.Today.ToShortDateString();
}
DateTime.TryParse
This I believe is faster and it means you dont have to use ugly try/catches :)
e.g
DateTime temp;
if(DateTime.TryParse(startDateTextBox.Text, out temp))
{
// Yay :)
}
else
{
// Aww.. :(
}
Don't use exceptions for flow control. Use DateTime.TryParse and DateTime.TryParseExact. Personally I prefer TryParseExact with a specific format, but I guess there are times when TryParse is better. Example use based on your original code:
DateTime value;
if (!DateTime.TryParse(startDateTextBox.Text, out value))
{
startDateTextox.Text = DateTime.Today.ToShortDateString();
}
Reasons for preferring this approach: