Saturday, May 9, 2009

VB.Net Convert String to Integer

It should be the simplest thing but you can come unstuck if you try to convert an empty string to an integer.

'The following conversions DO NOT work
Dim x1 As Integer = Convert.ToInt16("")
Dim x2 As Integer = Convert.ToInt32("")
Dim x3 As Integer = CInt("")
Dim x4 As Integer = CType("", Int32)

'The following conversions DO work
Dim x5 As Integer = Convert.ToInt32(Val(""))
Dim x6 As Integer = Convert.ToInt32(IIf(stringValue = "", 0, stringValue))

No comments: