Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 662
Faulty Orc Avatar asked Aug 24 '26 15:08

Faulty Orc


1 Answers

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.

like image 200
Jim Mischel Avatar answered Aug 26 '26 13:08

Jim Mischel