Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 Development Tools
 ASP.NET
 Min() / Max() date cast error from type DBNull

Author  Topic 

bubberz
Constraint Violating Yak Guru

289 Posts

Posted - 2005-09-12 : 18:25:05
When I run the following code I get:
Cast from type 'DBNull' to type 'Date' is not valid.

The datatype for the field is smalldatetime.
I can run it fine from SQL Server



Dim strSQL As String
strSQL = "SELECT MIN(ESDate) AS MinDate, MAX(EFDate) AS MaxDate FROM P3ActWBS WHERE "
strSQL &= "WBSNumber = '" & strWBSN & "'"
Dim cmd2 As New SqlCommand(strSQL, sCon1)
Dim DR2 As SqlDataReader = cmd2.ExecuteReader()
DR2.Read()
If DR2.HasRows = True Then

Dim strMinDate As Date = DR2(0)
Dim strMaxDate As Date = DR2(1)
DR2.Close()
DR2 = Nothing

jsmith8858
Dr. Cross Join

7423 Posts

Posted - 2005-09-13 : 08:49:22
As the error message says, the "Date" datatype in .NET cannot handle nulls. You need to explicitly handle the situation in which DR2(0) or DR2(1) returns DBNull and set your variables to valid dates.. i.e., you can use 1/1/1900 or something like that.

Also, you could create your own datatype that allows for Nulls. I believe vs 2005 implements nullable data types.

Finally -- why the heck have you prefixed your date variables with "str" ? It's bad enough, in general, to use datatype prefixes in variables in modern code, but even worse when you use the WRONG prefix ! Your code is very, very inconsistent in your naming conventions.
Go to Top of Page
   

- Advertisement -