开发者

CType and Type casting Exception

Public Property Duration() As Integer
Get
  Try
    Return CType(Item(DurationColumn), Integer)
  Catch e As Global.System.InvalidCastException
    Throw New Global.System.Data.StrongTypingException("The value for column 'Duration' in table 'T_MembershipSale' is DBNull.", e)
  End Try
End Get
Set(ByVal value As Integer)
  Item(DurationColumn) = value
End Set
End Property

What happens when a user wants to allocate "" as Item(DurationColumn) to integer? I get an exception. Any 开发者_StackOverflow社区clean solution to avoid this and set 0 for ""?


Use Int32.TryParse:

Dim number as Integer
If Not Int32.TryParse(DurationColumn, number) Then number = 0
return number

This handles the case of "", as well as any other invalid value (i.e. non-number) the user might enter.


You could assign function return to variable first then check variable before conversion.

    Dim sRet As String = Item(DurationColumn)
    If Not String.IsNullOrEmpty(sRet) Then Convert.ToInt32(sRet)


Look at TryCast and Int32.TryParse.


You can use IsNumeric

    number = If(IsNumeric(DurationColumn), CType(DurationColumn, Integer), 0)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜