ajordison
ajordison

Reputation: 55

Refresh a tree control and show the previously selected node

I have a VB.NET winforms application with a standard tree control on it. The tree control is refreshed every five seconds and I would like it so that if a node was selected, then it's selected after the refresh. Here's my code (m_oSelectedNode is a global treenode):

Public Sub SaveLabelNodes()
    m_cLabelTVNodes.Clear()

    If tvLabels.Nodes.Count = 0 Then
        Return
    End If
    m_LabelScrollPos = GetTreeViewScrollPos(tvLabels)
    m_oSelectedNode = tvLabels.SelectedNode
    m_bLabelRootExpanded = tvLabels.Nodes(0).IsExpanded
    For Each node As TreeNode In tvLabels.Nodes(0).Nodes
        Dim oNode As New NodeInfo
        oNode.bExpanded = node.IsExpanded
        oNode.szNodeName = node.Text
        m_cLabelTVNodes.Add(oNode)
    Next

End Sub

Public Sub RestoreLabelNodes()
    tvLabels.BeginUpdate()
    Dim nIndex As Integer = 0
    If m_bLabelRootExpanded Then
        tvLabels.Nodes(0).Expand()
    End If

    For Each oNode As NodeInfo In m_cLabelTVNodes

        If FindNode(tvLabels, oNode) Then
            If oNode.bExpanded Then
                tvLabels.Nodes(0).Nodes(nIndex).Expand()
            End If
        End If
        nIndex += 1
    Next
    If Not m_oSelectedNode Is Nothing Then
        tvLabels.SelectedNode = m_oSelectedNode
    End If
    SetTreeViewScrollPos(tvLabels, m_LabelScrollPos)

    tvLabels.EndUpdate()
End Sub

The tree control will scroll to the last position but the last selection will not select!

Upvotes: 1

Views: 1268

Answers (1)

user2480047
user2480047

Reputation:

You are storing m_oSelectedNode from the original information (before the nodes are deleted), which is not useful in the "new" TreeView. You have to rely on other information which will remain, for example: the name.

Dim m_oSelectedNode_NAME As String = tvLabels.SelectedNode.Name

And then in your loop:

For Each oNode As NodeInfo In m_cLabelTVNodes
    If FindNode(tvLabels, oNode) Then
       If oNode.bExpanded Then
          tvLabels.Nodes(0).Nodes(nIndex).Expand()
          if(tvLabels.Nodes(0).Nodes(nIndex).Name = m_oSelectedNode_NAME) Then
               tvLabels.SelectedNode = tvLabels.Nodes(0).Nodes(nIndex)
          Endif
       End If
    End If
    nIndex += 1
Next

This is just a generic solution, only taking children into consideration; you have to extend it to account also for main nodes (or children of children).

Upvotes: 2

Related Questions