VB.NET•Convert Complex Values Into a String and Back

Listing 2. The LatLong class is not a plain string, so you need the LatLongConverter class to convert its complex set of values into a string and back again.

Public Class LatLongConverter
   Inherits ExpandableObjectConverter

   Public Overloads Overrides Function _
      CanConvertFrom(ByVal context As _
      ITypeDescriptorContext, ByVal sourceType _
      As Type) As Boolean
      ' ----- Yes, we can handle strings.
      If (TypeOf (sourceType) Is String) Then _
         Return True
      Return MyBase.CanConvertFrom(context, _
         sourceType)
   End Function

   Public Overloads Overrides Function _
      CanConvertTo(ByVal context As _
      ITypeDescriptorContext, ByVal destType _
      As Type) As Boolean
      ' ----- Yes, we can go back to strings.
      If (TypeOf (destType) Is String) Then _
         Return True
      Return MyBase.CanConvertTo(context, _
         destType)
   End Function

   Public Overloads Overrides Function _
      ConvertFrom(ByVal context As _
      ITypeDescriptorContext, ByVal culture _
      As CultureInfo, ByVal value As Object) _
      As Object
      ' ----- Convert comma-delimited Lat/Long
      '       to class format.
      Dim sWork As String = CStr(value)
      Dim comma As Integer = sWork.IndexOf(","c)
      Return New LatLong(sWork.Substring(0, _
         comma).Trim, sWork.Substring( _
         comma + 1).Trim)
   End Function

   Public Overloads Overrides Function _
      ConvertTo(ByVal context As _
      ITypeDescriptorContext, ByVal culture _
      As CultureInfo, ByVal value As Object, _
      ByVal destType As Type) As Object
      ' ----- Convert LatLong back to a string.
      If (TypeOf (destType) Is String) And _
         (TypeOf (value) Is LatLong) Then
         ' ----- Build a return string.
         Dim workLatLong As LatLong = _
            CType(value, LatLong)
         Return workLatLong.Latitude & ", " & _
            workLatLong.Longitude
      End If
      Return MyBase.ConvertTo(context, culture, _
         value, destType)
   End Function
End Class