tags:

views:

111

answers:

6

I have code to parse Date Field only if String is not null or empty but I get the following Exception

Conversion from string " " to type 'Date' is not valid.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Conversion from string " " to type 'Date' is not valid.

Source Error:

Line 29:         
Line 30:  If (Not String.IsNullOrEmpty(last_login)) Then 
Line 31:    If  String.Format("{0:MM/dd/yy H:mm:ss}", last_login) < Now.AddMinutes(-5) Then
Line 32:      Return "height:100%;width:100% ;background-color:#FF0000;font-weight: bold; color: #000000"
Line 33:    Else

Anyone please explain?

+6  A: 

" " is not the empty string. (There's a space inside.) Perhaps you should call .Trim():

last_login != null && last_login.Trim().Length > 0

Or if you're using .NET 4, IsNullOrWhitespace is even better:

string.IsNullOrWhitespace(last_login)

Edited, thanks to @Anthony and @Joel.

Kirk Woll
Plus if you're on .NET 4, `string.IsNullOrWhitespace` is also useful.
Anthony Pegram
Joel Etherton
A: 

" " is a space, which is neither null nor empty. You can Trim() the string first, and then check for null, Empty, or Length == 0.

Wonko the Sane
A: 

It is not null or empty. It is a space. You could try trimming it.

Shiraz Bhaiji
+1  A: 

It seems like you need String.IsNullOrWhiteSpace(). I see a space character inside quotes.

max
which, it's worth pointing out, is new in .NET 4
Rup
+3  A: 

This is a mess. You're trying to use date formatting symbols on a string, to produce a string, to compare with a date.

Let's try this instead.

Dim dLast As DateTime
If ((Not last_login Is Nothing) AndAlso DateTime.TryParse(last_login.Trim(), dLast)) Then
    If (dLast < Now.AddMinutes(-5)) Then
        Return "height:100%;width:100% ;background-color:#FF0000;font-weight: bold; color: #000000"
    End If
End If

edit: check for null string before access it.

lincolnk
+1 - This is eliminates a lot of implicit casting (btw only works in VB) which speeds performance, plus it is significantly more bulletproof and less likely to cause a nasty exception farther down the road. Also, the .Trim() isn't needed with the DateTime.TryParse, it does it itself (plus it makes last_login = Nothing safe to run as well, as calling .Trim() on it will except if last_login is Nothing).
ben f.
A: 

.TryParse is fine with string = nothing

Dim dLast As DateTime
If DateTime.TryParse(last_login, dLast) Then
    If (dLast < Now.AddMinutes(-5)) Then
        Return "height:100%;width:100% ;background-color:#FF0000;font-weight: bold; color: #000000"
    End If
End If
dbasnett