0
votes

I am trying to validate two date of birth text box fields. If the member does not enter in these two boxes an error message will popped out like "pls enter valid date format"

When trying to save without entering the textbox values, it was showing error like this at Datetime DV.

String was not recognized as a valid DateTime.

private void btnCTimetablessave_Click(object sender, EventArgs e)
{
    string dob = tbStartDate.Text;
    DateTime dv;
    if (!DateTime.TryParse(dob, out dv))
    {

        MessageBox.Show("pls enter a valid  start date");
        return;
    }

    string format1 = dv.ToString("yyyy-MM-dd");
    string dob2 = tbEndDate.Text;
    DateTime dt2;
    if (!DateTime.TryParse(dob2, out dt2))
    {
        MessageBox.Show("pls enter valid end date");
        return;
    }

    string format2 = dt2.ToString("yyyy-MM-dd");

Still it was showing error at datetime Dv

"String was not recognized as a valid DateTime" ;

3
What kind of input is causing the error?Greg

3 Answers

2
votes

Obviously, tbStartDate.Text does not contain a valid Date. At least, according to your current environmental settings.

Localization might be a problem here. There's a good answer here: String was not recognized as a valid DateTime " format dd/MM/yyyy".

Update

Instead of using TryParse, you might want to use ParseExact:

DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);

That way, you can specify the input format you are expecting.

1
votes

What is the dbtype of the date parameter? You must set the value with an object of the same type of your argument.

0
votes

Even better than "TryParse" and "ParseExact" is "TryParseExact". And one of the overloads to TryParseExact takes a string array of format strings. So you can have even more flexibility on the input you accept. Also with the DateTimeStyles parameter you can specify additional flexibility in the white space that occurs within the string being parsed.