datatype conversion

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi

I have wrote code to pull a date from a database using a datareader
I keep getting a message that states that..
Cast from string "Null" to type 'Date' is not valid
Does anyone know how i can get rid of this message appearing

What i am trying to do is to retrieve 2 dates from my database. this is ok. I then want to make sure that both dates are not null (i.e a value exists for both dates). If a value exists for both dates i want to find the gap that exists between them in days
If any of the 2 dates are null i want to set the days gap to a value of 400

here is my code...

Dim ToDt As String = (reader1.GetSqlDateTime(0).ToString
Dim DeptDt As String = (reader2.GetSqlDateTime(0).ToString

Dim Gap As Int32
Dim GapArrayList as New ArrayList(
If Not (IsDBNull(ToDt) or IsDBNull(DeptDt)) The
Gap = DateDiff(DateInterval.Day, CDate(DeptDt), CDate(ToDt)
GapArrayList.Add(Gap
Els
GapArrayList.Add(400
End i
MsgBox(Gap
 
Bhavna said:
I have wrote code to pull a date from a database using a datareader.
I keep getting a message that states that...
Cast from string "Null" to type 'Date' is not valid.
Does anyone know how i can get rid of this message appearing?

What i am trying to do is to retrieve 2 dates from my database. this
is ok. I then want to make sure that both dates are not null (i.e a
value exists for both dates). If a value exists for both dates i want
to find the gap that exists between them in days.

Your way of checking whether or not the data is null is the problem, I
believe. Rather than converting the two SqlDateTimes to strings, you
should leave them as SqlDateTimes and check each of them with the
IsNull property.

You can then get the value as a DateTime with the Value property of the
SqlDateTime, and subtract one DateTime from the other to get a TimeSpan
representing the difference between the two. There's no need to format
the dates as strings and then parse them again.
 
Hi Jo

i tried to do this..
Dim ToDt As DateTime = (reader1.GetSqlDateTime(0)

but the code in parenthesis gets underlined and i get a message that says
Value of type 'System.Data.SqlTypes.SQLDateTime' cannot be converted to 'Date'
what have i done wrong
It is for this reason that i used the tostring!!

Do u know a way around this?
 
Bhav said:
i tried to do this...
Dim ToDt As DateTime = (reader1.GetSqlDateTime(0))

but the code in parenthesis gets underlined and i get a message that says:
Value of type 'System.Data.SqlTypes.SQLDateTime' cannot be converted to 'Date'.
what have i done wrong?

You've declared that type of ToDt as DateTime, when GetSqlDateTime
returns SqlDateTime.
It is for this reason that i used the tostring!!!

Not understanding an error message is *never* a good reason to just
move to another design.
Do u know a way around this?

Declare ToDt as type SqlDateTime, and when you need a DateTime from it,
use the Value property to get it.
 
Back
Top