Date variables and nothing/null



I'm unsure how best to handle dates from my webforms to my database.

Often I have a textbox and a datepicker on a webform. Upon postback
dates are received in string format (like DD-MM-YYYY). Ultimately the
dates need to be stored in a datetime/smalldatetime field in the sql
server. However, first I pass then dates to the db via a business
layer where the date properties are of type datetime.

I've explored several ways to handle this scenario, but am unsure
which of the ways are the "best".

Should I first:
1) enter the posted textbox.text into a string variable,
2) try catch type cast the string variable into a datetime variable
(if the type cast fails should I set the datetime property of the
business layer to null/nothing? / or how should optional dates be




Kevin Spencer

First you need to determine the business rules for your app. Is the DateTime
filed required? Are there any constraints on the range of dates?

Second, you need to use Form validation to enforce those rules. Do not allow
the form to be posted if any of them are broken. Do not allow the form to be
posted if the value in it is not a valid DateTime string. In fact, the best
strategy in an ASP.Net app for getting DateTime data from the user is to use
a Calendar Control. It builds the DateTime value for you, and does not
require the user to type (and therefore mistype) the date.


Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.


Hi Morten,

I agree Kevin’s suggestion. Calendar control definitely gives you a valid
date value. But sometimes, end-users don’t like use Calendar control to
pickup date. In that case, you can use textbox and RegularExpressionValidator
control. Following is a very simple Date Regular Expression:


Validator control can validate data on client-side.


Elton Wang

Andy Fish

in addition to the other two suggestions, I use a convention inside the
business layer that a value of DateTime.MinValue in the code corresponds to
NULL on the database. That way you can parse date strings at the earliest
opportunity and safely handle blank dates inside the code.





Thanks for your input... I was struggling with passing dates through
my business layer. Eventually, I ended up using datetime.minvalue to
handle null/nothing.

On the client side I'm using a datepicker, but users still want to
enter text, compare and regex validators and custom js.

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question