【发布时间】:2018-06-27 21:39:35
【问题描述】:
我正在创建一个在 VB.NET 中使用 TreeListView 的简单示例(或至少一个我可以遵循的示例),但我遇到了一个问题。当我运行下面的代码时,最初一切正常。我有一棵带有宠物名字分支的宠物主人树。但是在我展开其中一个节点并移动鼠标后,我收到一条错误消息,告诉我无法将字符串对象转换为 petowner 对象(我的对象类)。我明白这意味着什么,但 VS 并没有告诉我错误在哪里,我也不能将它困在 try-catch 中。我正在寻找一些见解。
另外:谁能告诉我我从 C# 到 VB 的转换是否正确;特别是 lambda 函数代替 ChildrenGetter 和 AspectGetter 方法中的委托?我相当肯定这就是错误所在。
提前致谢。
Public Class Form1
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Dim PetOwners As New List(Of PetOwner)
Dim PetOwner As PetOwner
PetOwner = New PetOwner
PetOwner.OwnerName = "Steve"
PetOwner.PetNames.Add("Bob the Cat")
PetOwner.PetNames.Add("Snoop the Dog")
PetOwners.Add(PetOwner)
PetOwner = New PetOwner
PetOwner.OwnerName = "Ann"
PetOwners.Add(PetOwner)
PetOwner = New PetOwner
PetOwner.OwnerName = "Joe"
PetOwner.PetNames.Add("Shoeless")
PetOwners.Add(PetOwner)
Try
tlvPetOwners.CanExpandGetter = Function(po As PetOwner) po.PetNames.Count > 0
tlvPetOwners.ChildrenGetter = Function(po As Object)
Dim RetVal As Object = Nothing
Try
If TypeOf po Is PetOwner Then
RetVal = CType(po, PetOwner).PetNames
Else
RetVal = po
End If
Catch ex As Exception
Debug.Print(ex.ToString)
Finally
End Try
Return RetVal
End Function
Dim OwnerColumn As New OLVColumn()
OwnerColumn.AspectGetter = Function(po As Object)
Dim RetVal As Object = Nothing
Try
If TypeOf po Is PetOwner Then
RetVal = CType(po, PetOwner).OwnerName
Else
RetVal = po
End If
Catch ex As Exception
Debug.Print(ex.ToString)
Finally
End Try
Return RetVal
End Function
tlvPetOwners.Columns.Add(OwnerColumn)
tlvPetOwners.Roots = PetOwners
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
End Sub
End Class
Public Class PetOwner
Public OwnerName As String
Public PetNames As New List(Of String)
End Class
【问题讨论】:
-
然后在你的代码上插入断点,然后调试你会发现哪里出错了。
-
没错,但是 column aspectgetter 方法似乎处于连续循环中。按F5一会儿后。当它停止并且我重新进入 TreeListView 时,循环重新开始,我继续按 F5 一会儿。当然,我从来没有遇到过错误。
-
抱歉,不是很清楚。循环最终会停止,但是当我用光标重新进入 TreeListView 时,循环会重新开始。我可以做到这一点,因为这似乎是永恒的,而且永远不会出错。直到我删除断点,它才会出错,但不会告诉我在哪里,也不会在任何 Try 子句中遇到异常。
-
好的,我将在我的窗口中尝试此代码。
标签: .net vb.net treelistview