This is a migrated thread and some comments may be shown as answers.

How to programmatically remove a child tree node?

3 Answers 1533 Views
TreeView
This is a migrated thread and some comments may be shown as answers.
Robert
Top achievements
Rank 1
Robert asked on 22 Oct 2012, 08:26 PM
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

3 Answers, 1 is accepted

Sort by
0
Accepted
Pavel R. Pavlov
Telerik team
answered on 25 Oct 2012, 09:14 AM
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.

0
Robert
Top achievements
Rank 1
answered on 25 Oct 2012, 01:50 PM

Thanks Pavlov, your solution works well.

All the best,

Rob

0
Karthi
Top achievements
Rank 1
answered on 07 Mar 2015, 11:27 AM
I had tried these code.. But i got error
Tags
TreeView
Asked by
Robert
Top achievements
Rank 1
Answers by
Pavel R. Pavlov
Telerik team
Robert
Top achievements
Rank 1
Karthi
Top achievements
Rank 1
Share this question
or