I have a class (called Location) that has three properties and I want to be able to use it as a
regular type elsewhere in my code, such as assigning a string to it and getting a string from
it. Similar to the following:
Dim a as Location
a = "112|nyk|new york"
I have tried writing a TypeConverter for it (shown below) but when I try the statements
above, it gives me
Value of type 'String' cannot be conerted to 'sandbox4.Location'.
I thought the TypeConverter would allow that to happen. Am I missing something? (And
yes, I have read the docs regarding Implementing a TypeConverter for a point (and one
for a circle, but that did not help...)
Thanks.
LocationConverter.vb
Imports System.Globalization
Imports System.ComponentModel
Public Class LocationConverter
Inherits TypeConverter
Public Overloads Overrides Function CanConvertFrom(ByVal context As ITypeDescriptorContext, ByVal sourceType As Type) As Boolean
If sourceType Is GetType(String) Then
Return True
End If
Return MyBase.CanConvertFrom(context, sourceType)
End Function
Public Overloads Overrides Function ConvertFrom(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object) As Object
If TypeOf value Is String Then
Dim v As String() = CStr(value).Split("|")
Return New Location(Integer.Parse(v(0)), v(1), v(2))
End If
Return MyBase.ConvertFrom(context, culture, value)
End Function
Public Overloads Overrides Function ConvertTo(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object, ByVal destinationType As Type) As Object
If destinationType Is GetType(String) Then
Return CType(value, Location).LocNum & "|" & CType(value, Location).Abbrv & _
"|" & CType(value, Location).Name
End If
Return MyBase.ConvertTo(context, culture, value, destinationType)
End Function
End Class
Location.vb
Imports System.ComponentModel
<TypeConverter(GetType(LocationConverter))> _
Public Class Location
Private _locNum As Integer
Private _Abbrv As String
Private _Name As String
Property LocNum() As Integer
Get
LocNum = _locNum
End Get
Set(ByVal Value As Integer)
_locNum = Value
End Set
End Property
Property Name() As String
Get
Name = _Name
End Get
Set(ByVal Value As String)
_Name = Value
End Set
End Property
Property Abbrv() As String
Get
Abbrv = _Abbrv
End Get
Set(ByVal Value As String)
_Abbrv = Value
End Set
End Property
Public Sub New()
End Sub
Public Sub New(ByVal locNumber As Integer, ByVal Abbrev As String, ByVal LocName As String)
_locNum = locNumber
_Abbrv = Abbrev
_Name = LocName
End Sub
Public Sub New(ByVal str As String)
Dim v() As String = str.Split(ControlChars.Tab)
_locNum = CInt(v(0))
_Abbrv = v(1)
_Name = v(2)
End Sub
End Class
Sample.vb
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim a As Location
a = New Location(1, "a", "alba")
' other code here .....
' THIS IS THE LINE THAT GIVES ME THE ERROR MESSAGE
a = "112|NYK|NEW YORK"
' other code here .....
End Sub