0

I have a C# window application to fill in Date of Birth and send the data to my database with type datetime. Here is the code:

DateTime dateOfBirth;
try
{
    dateOfBirth = new DateTime(int.Parse(textBox54.Text), int.Parse(textBox53.Text), int.Parse(textBox52.Text));
}
catch (Exception ex)
{
    MessageBox.Show("Invalid");
    return;
}

It works fine with proper date, but when I randomly test my application and fill in "234" for Year, datetime from varchar conversion out of range error occurs in the statement

cm.ExecuteNonQuery();

How can I catch it? Thanks.

AkariKamigishi
  • 277
  • 7
  • 23

1 Answers1

0

You can use DateTime.TryParseExact:

Updated:

    string inputDate = int.Parse(textBox54.Text)+"-"+int.Parse(textBox53.Text)+"-"+int.Parse(textBox52.Text);
    DateTime dateOfBirth ;

    var DateFormat = new[] { "dd/MM/yyyy", "yyyy-MM-dd" };
    if (DateTime.TryParseExact(inputDate, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateOfBirth ))
    {

       //Valid Date
      //Call DB here
    }
    else
    {

        // Invalid Date
    }
Ken Clark
  • 2,500
  • 15
  • 15
  • @Habib you are right. Updated answer. This will first check if inputDate will be valid date then can be use for further processing. – Ken Clark Mar 22 '13 at 09:34
  • 1
    It still cant catch the error when I input "234" for Year because it's a valid date for C# but not SQL – AkariKamigishi Mar 22 '13 at 09:44
  • @KenClark, the issue here is not parsing the date in C#, its about SQL server throwing exception since date range for both .Net framework and SQL server is different. – Habib Mar 22 '13 at 09:51