Help with seemingly easy task with a treeview

TyB

Well-known member
Joined
May 14, 2009
Messages
102
Programming Experience
3-5
Hello all,
I thought this would be simple but it has turned out to be some what troublesome.

I have a treeview like so.

VB.NET:
Hi im parent
   Im child1
   Im child2

I want to delete child1 from the treeview then change the text of the parent to what the deleted childs text was essentially making the child the new parent so it would look like this.

VB.NET:
Im child1
    Im child2
I tried the following but it always seems to delete the entire treeview.

VB.NET:
'Remove the child from the treeview as we are making it the parent now. 
            TreeView1.SelectedNode.Text = "Im child1"
            TreeView1.Nodes.Remove(TreeView1.SelectedNode)


            'Make the child the parent node.
            TreeView1.SelectedNode.Text = "Im child1"

I would have thought that the first part would have made the child the selected node but I think it is just changing the name of the parent node then deleting it thus deleting all the node.

Thanks for your help.

Ty
 
It will be variations of this; this gets a reference to the first child of the first root node, removes the first root node, then adds the first child to root:
VB.NET:
Dim node As TreeNode = Me.TreeView1.Nodes(0).Nodes(0)
Me.TreeView1.Nodes.RemoveAt(0)
Me.TreeView1.Nodes.Add(node)
What you mean by rearranging the child1s sibling child2 to be a child of child1 is not clear. I don't see what logical rule you would base such arrangement on.
 
Here is the answer for those that are interested

This part first calls the find function then uses the return value for the delete statement.

VB.NET:
Dim nodes As New TreeNode

            nodes = FindNode(TreeView1.SelectedNode, TextBox3.Text)

            TreeView1.Nodes.Remove(nodes)

This is the function that finds the node we want to delete.

VB.NET:
    Public Function FindNode(ByVal ParentNode As TreeNode, ByVal SearchVal As String) As TreeNode
        Dim tmpNode As TreeNode

        If ParentNode.Text = SearchVal Then
            Return ParentNode
        Else
            Dim child As TreeNode
            For Each child In ParentNode.Nodes
                tmpNode = FindNode(child, SearchVal)
                If Not tmpNode Is Nothing Then
                    Return tmpNode
                End If
            Next
        End If

        Return Nothing
    End Function

Thanks,
Ty
 
Back
Top