I have three text boxes on a form to capture MM, DD and YYYY. I've set up range validators on the form so that MM can only be between 1 and 12, DD between 1 and 31 and YYYY between 1900 and 2010. Ultimately the data is stored in the database in the decimal format of MMDDYY (legacy design that I can't change yet), but I want implement some further validation of the date (such as 02/29/2010 is not a valid date), so here was my stab at doing so.
| if (admitDDTextBox.Text != "" & admitMMTextBox.Text != "" & admitYYYYTextBox.Text != "") { string admitStringDate = string.Concat(txtMMadmit, "/", txtDDadmit, "/", txtYYYYadmit); try { DateTime admitDateConverted = Convert.ToDateTime(admitStringDate); } catch (DataException ex) { lblError.Text = "Admit Date Not a Valid Date. Please Correct Admit Date and Resubmit"; } } |
When I try running this in debugger with invalid date input, it just stops at the Convert.ToDateTime, indicating there is an error in the date format string. With a valid date, the program just proceeds on as it normally should.
How can implement a check to determine if the date is valid and throw a message back to the user, using only C# to get it done?
Thanks for any/all help.
Charbel AbdoPosted Feb 4, 2010, 10:13 AM
DateTime myDate = new DateTime();
bool validDate = DateTime.TryParse(admitStringDate , out myDate);
try parse returns false if parsing fails,and put the result in the out variable (myDate)
Also, try replacing catch (dataException) with catch (exception) or catch (invalidCastException)
Todd BurrellPosted Feb 4, 2010, 10:30 AM
if (validDate == false)
{
lblError.Text = "Admit Date Not a Valid Date. Please Correct Admit Date and Resubmit";
return;
}
and this seems to have worked fine, in limited testing.