Reputation: 6545
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?
Upvotes: 1
Views: 313
Reputation: 11773
.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
Upvotes: 1
Reputation: 11238
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.
Upvotes: 3
Reputation: 77546
" "
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.
Upvotes: 6
Reputation: 34407
It seems like you need String.IsNullOrWhiteSpace()
. I see a space character inside quotes.
Upvotes: 1
Reputation: 65391
It is not null or empty. It is a space. You could try trimming it.
Upvotes: 0
Reputation: 10813
" " is a space, which is neither null nor empty. You can Trim() the string first, and then check for null, Empty, or Length == 0.
Upvotes: 0