How to programmatically remove a child tree node?

4 posts, 1 answers
  1. Robert
    Robert avatar
    271 posts
    Member since:
    Mar 2011

    Posted 22 Oct 2012 Link to this post

    Hi,

    I'm having trouble trying to remove a treeview item programmatically.

    I add tree items roughly like so:
    RadTreeViewItem item = new RadTreeViewItem();
    item.Header = "Header 1";
    item.Tag = myProperty;
     
    treeProducts.Add(item);


    I then try to use the following method to remove the desired TreeItem:
    //Get Selected Tree Item
    RadTreeViewItem treeViewItem = (RadTreeViewItem)treeProducts.SelectedItem;
    //Remove TreeView Item
    this.treeProducts.Items.Remove(treeViewItem);


    For some reason it will only remove "TOP LEVEL" tree items and not items that are child nodes.

    Do you know how I can programmatically remove a TreeItem that isn't a top level node?

    I can see that it has something to do with the RadTreeView Items Collection, where it only lists all top level nodes.

    Thank you for time,

    Rob
  2. Answer
    Pavel R. Pavlov
    Admin
    Pavel R. Pavlov avatar
    1182 posts

    Posted 25 Oct 2012 Link to this post

    Hi Robert,

    Your issue is caused by the fact that all children of an RadTreeViewItem are placed in a nested ItemsCollection and the RadTreeView.Items.Remove() method is not searching in that collection. However, in order to delete a child node you have to get the item(s) manually:
    //Get Selected Tree Item
    RadTreeViewItem treeViewItem = (RadTreeViewItem)treeProducts.SelectedItem;
     
    if (treeViewItem == null)
    {
        return;
    }
    //Get the parent of the treeViewItem
    if (treeViewItem.Parent is RadTreeViewItem)
    {
        (treeViewItem.Parent as RadTreeViewItem).Items.Remove(treeViewItem);
    }
    else
    {
        //Remove TreeView Item
        this.treeProducts.Items.Remove(treeViewItem);
    }
    You can examine the approach in this online demo.

    Please give it a try and let me know if you have any other questions.

    Kind regards,
    Pavel R. Pavlov
    the Telerik team

    Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

  3. UI for WPF is Visual Studio 2017 Ready
  4. Robert
    Robert avatar
    271 posts
    Member since:
    Mar 2011

    Posted 25 Oct 2012 Link to this post

    Thanks Pavlov, your solution works well.

    All the best,

    Rob

  5. Karthi
    Karthi avatar
    1 posts
    Member since:
    Mar 2015

    Posted 07 Mar 2015 in reply to Pavel R. Pavlov Link to this post

    I had tried these code.. But i got error
Back to Top