3
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 clean solution to avoid this and set 0 for ""?

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
Faulty Orc
  • 955
  • 4
  • 13
  • 24

4 Answers4

3

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.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
0

Look at TryCast and Int32.TryParse.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Rob P.
  • 14,921
  • 14
  • 73
  • 109
0

You can use IsNumeric

    number = If(IsNumeric(DurationColumn), CType(DurationColumn, Integer), 0)
Echilon
  • 10,064
  • 33
  • 131
  • 217
Fredou
  • 19,848
  • 10
  • 58
  • 113
  • That won't work. According to http://msdn.microsoft.com/en-us/library/6cd3f6w1.aspx, "IsNumeric will also return True if the string being checked is a number containing a comma or a dollar sign". It also returns True if it's a floating-point number or a number that's larger than will fit into an integer (i.e. a Long or ULong). – Jim Mischel Feb 25 '11 at 18:20
  • @Jim Mischel, issue described is check for "", not for overflow or something else. I understand your point but this snippet of code does actually work – Fredou Feb 25 '11 at 18:55
0

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)
dev93
  • 11
  • 1