# .NET and More > WPF, WCF, WF >  How to find parent of selected item in TreeView?

## HongKongCV

Okay, using Windows 7 with VS2012 and .NET 4.5 in a WPF application, I have a multi-level treeview that looks like this:



The TreeView is bound to an observable collection of the codes. What I want SHOULD be simple, but it's not turning out to be so. Let's assume that the user clicks on the "6010F-8P" item... how can I find the parent item ("6015F-00")? The data can be up to four levels deep, and I need to be able to backtrack up the entire chain to find not only the root item, but also each parent along the way.

I have searched and searched, but can't find any way to do this. Is there any way for the TreeView control to do find the parent item of a selected item?

Thanks in advance...

----------


## dday9

To get the item's parent is simple it's like this:


```
Dim parent As TreeNode = currentNode.Parent
```

However if you're wanting to get every parent up the chain, it'd go something like this(I'm free-typing it by the way so there may be a typo):


```
Private Function GetParents(ByVal currentNode As TreeNode) As TreeNode()
    'Create a new instance of a List(Of TreeNode)
    Dim chain As List(Of TreeNode) = New List(Of TreeNode)

    'Declare a variable to hold the parent node
    Dim nextNode As TreeNode = currentNode.Parent

    'Add the initial parent to the List(Of Node)
    chain.Add(nextNode)

    Do
        'The next node will be the current node that we are on's parent
        nextNode = nextNode.Parent

        'If the next node is something then add it to the List(Of Node)
        If nextNode IsNot Nothing Then
           chain.Add(nextNode)
        End If

        'Exit the loop if the next node is nothing
    Loop Until IsNothing(nextNode)

    'Return the array of nodes
    Return chain.ToArray()
End Function
```

With that function, the first item in the array will be the current node's parent and the last item will be the ultimate root item.

----------


## HongKongCV

Okay, so how do I get the currently selected row as a TreeNode?

BTW, the WPF TreeView doesn't seem to have anything to do with TreeNodes. The WPF TreeView control comes from System.Windows.Controls, and there is no System.Windows.Controls.TreeNode that I can find. Please tell me that the WPF TreeView supports what I need to do...

----------


## dday9

Ah... I did not see that this was WPF(I should've read better). I'll move this thread to the WPF forum.

----------

