开发者

Weird situation with Empty String

I have code to parse Date Field only if String is not null or empty but I g开发者_如何学编程et 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?


" " 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.


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.


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


.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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜