0

I have user registration form. It has field Date of birth. It is not compulsory in database also not on UI. But while create when i am goiing to assign it to objects property, i have to convert it in to date format. But if i have not selected it, it will become null in the FormCollection object. like

User.DOB=Convert.ToDateTime(collection["DOB"]);

Now issue is if it collection["DOB"]is null then it throws exception. I can not assign default value here. So how can i handle this situation?

1 Answer 1

2

You'll probably be better off using DateTime.TryParse for this.

This way you can check whether you're working with a valid date or not.

DateTime dateOfBirth;

bool isValidDateOfBirth = DateTime.TryParse(collection["DOB"], out dateOfBirth);

if(isValidDateOfBirth)
{
 // do stuff
}
else
{
 // do some other stuff
}
Sign up to request clarification or add additional context in comments.

4 Comments

Or, why bother creating the bool when you could just check the direct output of the TryParse - if(DateTime.TryParse...).
You can do that also. I included the bool here to make it explicitly clear to the OP what's going on. I don't know their skill level so I find this aproach (being a bit more expansive) to be quite useful.
I agree, but what if collection have null value, so what action have to take ?generally what developers does, if there is no defaults, and date is mandatory in DB?
If you're collecting data from a form that is required, both client side and server side validation need to be performed. There are many ways you can do this. Here's one of those ways: weblogs.asp.net/scottgu/archive/2010/01/15/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.