properly passing DBNull.value to DB via a variable

D

darrel

A common problem I encounter is having to enter either a date OR a null
value into a date field in a DB.

The problem I hace is that DBNull.value isn't a proper value for a date
variable, so I can't explicitely declare the variable:

Dim myDateVariable
If Trim(tbx_postDate.Text.ToString) <> "" Then
myDateVariable= CType(tbx_postDate.Text.ToString, Date)
Else
myDateVariable= DBNull.Value
End If

Is that OK to not specifically declare the datatype for myDateVariable? Is
there a more elegant way to handle this?

-Darrel
 
K

Karl Seguin

It's a bad problem with no great solutions. Nullable types in 2.0 _should_
solve the problem, except a null nullable type does NOT map to DbNull - what
were they thinking?

Anyways, that point asside, I generally just use a helper method:

command.Parameters.Add("@Data", SqlDbType.DateTime).Value =
SanitizeDateTime(dateValue)

public shared function SanitizeDateTime(string dateStringValue) as object
if...
return the date
end if
return DBNull.Value
end function

Karl
 

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

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top