TryCast返回与我期望的相反

时间:2014-03-01 19:13:47

标签: vb.net

请查看以下代码:

Imports DataObjects  
Imports BusinessObjects  
Public Class FormMain
Private Sub FormLogin_Load(sender As Object, e As EventArgs) Handles Me.Load
    'InitializeTreeView()
    TreeViewMembers.Nodes.Add("Members")
End Sub

Private Sub InitializeTreeView()
    'Dim objMemberDAO As New MemberDAO
    'Dim theMembers = objMemberDAO.GetMembers
    Dim model As New Model
    Dim theMembers = model.GetMembers()
    For Each member In theMembers
        TreeViewMembers.Nodes(0).Nodes.Add(member.name)
        TreeViewMembers.Nodes(0).Tag = member
    Next member
End Sub

Private Sub TreeViewMember_AfterSelect(ByVal sender As Object, ByVal e As TreeViewEventArgs) Handles TreeViewMembers.AfterSelect
    Try
        InitializeTreeView()
        Dim member = TryCast(TreeViewMembers.SelectedNode.Tag, MemberModel)
        If member Is Nothing Then
            Return
        End If
        'BindLoans(member.Loans)
    Catch EX As Exception
        MsgBox(EX.ToString)
    End Try
End Sub

End Class

第一次加载表单时,TryCast返回一个MemberModel。当我从TreeView中选择一个成员时,它返回Nothing。这与我的期望相反。我做错了什么?

1 个答案:

答案 0 :(得分:0)

据我了解您的代码,错误似乎在这个块中:

For Each member In theMembers
    TreeViewMembers.Nodes(0).Nodes.Add(member.name)
    TreeViewMembers.Nodes(0).Tag = member
Next member

此代码设置根节点上的标记,而不是新创建的节点上的标记。因此,错误与TryCast无关。这可以按预期工作 - 当代码第一次运行时,您必须选择为其设置模型的根节点(在第一个版本中)。所以TryCast返回一个模型。

选择其他成员时,标记未设置,因此TryCast将返回Nothing(输入Nothing =>输出Nothing)。

我认为更改这样的代码应该会有所帮助:

For Each member In theMembers
    Dim newNode = TreeViewMembers.Nodes(0).Nodes.Add(member.name)
    newNode.Tag = member
Next member