Polymorphic DataBinding

mwightman

Member
Joined
Aug 18, 2007
Messages
9
Programming Experience
10+
I am attempting to bind a grid to a list of object but I am unable to resolve an exception

*************Exception*****************

Object does not match target type.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Reflection.TargetException: Object does not match target type.

Source Error:

Line 17: With GridView1
Line 18: .DataSource = L
Line 19: .DataBind()
Line 20: End With
Line 21:


************CODE**************


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim L As New Animals
L.Add(New Cat("Oscar"))
L.Add(New Cat("Moris"))
L.Add(New Dog("Snoopy"))
L.Add(New Dog("Droopy"))


With GridView1
.DataSource = L
.DataBind()
End With
End Sub


Public Class Animals : Inherits List(Of Animal) : Implements System.ComponentModel.ITypedList


Public Function GetItemProperties(ByVal listAccessors() As System.ComponentModel.PropertyDescriptor) As System.ComponentModel.PropertyDescriptorCollection Implements System.ComponentModel.ITypedList.GetItemProperties
Return System.ComponentModel.TypeDescriptor.GetProperties(GetType(Animal))
End Function

Public Function GetListName(ByVal listAccessors() As System.ComponentModel.PropertyDescriptor) As String Implements System.ComponentModel.ITypedList.GetListName
Return GetType(Animal).Name
End Function
End Class


Public MustInherit Class LivingThing

Private _Id As Guid

Public Sub New()
_Id = Guid.NewGuid
End Sub

Public ReadOnly Property ID() As Guid
Get
Return _Id
End Get
End Property


End Class



Public MustInherit Class Animal : Inherits LivingThing

Private _Name As String

Public Sub New(ByVal Name As String)
MyBase.New()
_Name = Name

End Sub

Public ReadOnly Property Name() As String
Get
Return _Name
End Get
End Property

Public MustOverride ReadOnly Property Type() As String
Public MustOverride Function Speak() As String

End Class

Public Class Dog : Inherits Animal

Public Sub New(ByVal Name As String)
MyBase.New(Name)
End Sub

Public Overrides ReadOnly Property Type() As String
Get
Return "Dog"
End Get
End Property

Public Overrides Function Speak() As String
Return "Woof"
End Function
End Class


Public Class Cat : Inherits Animal

Public Sub New(ByVal Name As String)
MyBase.New(Name)
End Sub

Public Overrides ReadOnly Property Type() As String
Get
Return "Cat"
End Get
End Property

Public Overrides Function Speak() As String
Return "Meow"
End Function
End Class
 
Back
Top