Party like it's 1/1/1900

Bookmark and Share

(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

Tags

//

No TrackBacks
TrackBack URL: http://www.codescene.com/cgi-bin/mt/mt-tb.cgi/10

Leave a Comment

Free the web - Boycott Internet Explorer 6