chris
chris

Reputation: 19

Date Time exception

I made a registration page where users input personal details to make an account. But I keep getting an exception and my application with the control validation do not work at all!!

protected void btnSubmit_Click(object sender, EventArgs e)
{
    Registration _m = new Registration();
    DateTime dateOfBirth = DateTime.ParseExact(txtDOB.Text, "dd/MM/yyyy", null);
    lblMsg.Text = _m.Register(txtUser.Text, txtTitle.Text, txtPass.Text, 
    txtMidI.Text, txtSur.Text, txtCity.Text, txtPostCode.Text, txtxMobile.Text, 
    txtLandL.Text, txtEmail.Text, RBLMF.SelectedValue, dateOfBirth, 
    RBLYesNo.SelectedValue, txtSQ.Text, txtxAn.Text);
}

Exception says :

 String was not recognized as a valid DateTime.

Upvotes: 0

Views: 83

Answers (2)

cost
cost

Reputation: 4490

It looks like your conversion from string to date is failing. Since you're pulling this data from a textbox, that means the input could theoretically be anything, so you should always validate it. Take a look at DateTime.TryParseExact. I haven't tested this code, but roughly what you want to do is change

DateTime dateOfBirth = DateTime.ParseExact(txtDOB.Text, "dd/MM/yyyy", null);

To

DateTime dateOfBirth;
if (DateTime.TryParseExact(txtDOB.Text, "dd/MM/yyyy", null, DateTimeStyles.None, out dateOfBirth)))
{
  //Do your logic in here
  //.....
}
else
{
  //Show a message to the user that they didn't enter a valid date
  //.....
}

Upvotes: 3

sevzas
sevzas

Reputation: 801

Using "d/M/yyyy" is more flexible since it allows users to enter single-digit month and day.

Upvotes: -2

Related Questions