Search code examples
wpftreeviewtreeviewitem

TreeView get selected node issue


Trying to get the parent and child node headers that was selected in the treeview but I get the error that it can't convert string to TreeViewItem.

private void tvSQLTasks_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        //error is here
        TreeViewItem child = (TreeViewItem)tvSQLTasks.SelectedItem;

        if (child.Parent is TreeViewItem)
        {
            TreeViewItem parent = (TreeViewItem)child.Parent;

            SQLTask _task = SQLTasks.Where(t => t._rootNode.Equals(parent.Header.ToString()) && t._childNode.Equals(child.Header.ToString())).FirstOrDefault();

            if (_task != null)
            {
                txtTaskDescription.Text = _task._taskDescription;
            }
        }
    }

Here is how i'm adding the nodes

      private void AddRootNode(string _nodeName)
    {
        tvSQLTasks.Items.Add(new TreeViewItem() { Header = _nodeName });
    }

    private void AddChildNode(string _rootNode, string _childeNode)
    {
        foreach (TreeViewItem node in tvSQLTasks.Items)
        {
            if (node.Header.Equals(_rootNode))
            {
                (node as TreeViewItem).Items.Add(_childeNode);
            }
        }
    }

Solution

  • This seems to be the problem line:

     (node as TreeViewItem).Items.Add(_childeNode);
    

    Try changing it to:

     node.Items.Add(new TreeViewItem() { Header = _childeNode});