Why is this page text-only?

Party like it's 1/1/1900

(or how to insert null values into SQL using ASP.NET)
I've built several online applications using Microsoft SQL Server as the backend database and one thing that's always given me trouble was inserting dates, or more specifically NOT inserting dates.
Users can enter a date or use a calendar control to select one and, assuming it's valid, it goes into the database with no problems. But what happens when the user leaves the date field blank? If SQL is expecting a date, and you pass it a null value instead, it ends up in the database as the SQL default date of 1/1/1900 when most often you just want it left blank.

So how do you insert a blank value into the database? Here's an easy trick using VB.NET (assuming txtDate is an asp:TextBox)

<%@ import namespace="System.Data.SqlTypes" %>

Dim nulldate As SqlDateTime
nulldate = SqlDateTime.Null

If (txtDate.Text = String.Empty) Then
    cmd.Parameters("@Date").Value = nulldate
Else
    cmd.Parameters("@Date").Value = txtDate.Text
End If

Del.icio.us Digg Yahoo! My Web Seed Newsvine reddit Technorati Facebook StumbleUpon Mark in ma.gnolia Google Bookmarks Windows Live

TrackBacks

TrackBack URL for this entry:
http://www.codescene.com/cgi-bin/mt/mt-t.cgi/9

Leave a comment