Date time control

  • Thread starter Thread starter Baris - Izmir
  • Start date Start date
B

Baris - Izmir

Hi,

I have a web form and this form takes a date data from user and stores
it to database (SQL). I written a store procedure to perform this but
when I do not fill the date textbox, SQL gives an error message about
filling the date textbox. In SQL I checked "accept null" for the date
column. What can I do?

Thanks.
 
When you do something like this:

cmd.Parameters.Add("@DateName", txtDateBox.Text);

you will end up with String.Empty as a value many times. There are a couple
of ways to handle this, but here is my suggestion (or something similar as I
am shooting from the hip here):

SqlDateTime dt;

if(txtDateBox.Text.Trim() == String.Empty)
dt = SqlDateTime.Null;
else
dt = new SqlDateTime(Convert.ToDateTime(txtDateBox.Text));

You will likely want to validate the date first, as some entering
"asjdflksajdlf" into the textbox with throw an exception, but this idea
should get you started.

Rule #1: Never trust user input
Rule #2: Be explicit (in this case casting to a SqlType is safest)

NOTE: This assumes SQL Server. For other tproviders, use the correct
datatypes.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

************************************************
Think Outside the Box!
************************************************
 
Back
Top