Todd Burrell

Todd Burrell

  • NA
  • 15
  • 0

Validating Date Conversion

Feb 4 2010 7:42 AM
I'm still a C Sharp rookie and I need a little help trying to implement the validation of a Convert.ToDateTime routine. 

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.


Answers (2)