0

How to delete all sub node in the some treenode?

TTreeNode* ParentNode = TreeView->Selected;
int countNode = ParentNode->Count;
for(int p=0; p<countNode-1; p++)
{
    ParentNode->Item[p]->Delete();
}

this code dosn't work!

Dalija Prasnikar
  • 27,212
  • 44
  • 82
  • 159

2 Answers2

0

Call DeleteChildren on the parent node:

ParentNode->DeleteChildren();
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

David gave you the right answer (use TTreeNode::DeleteChildren()), but you should also understand why your original code was failing so you don't make the same mistake again later.

You were looping forwards from first child to last child, deleting each node as you went along. Every time you deleted a child, the parent node's Count decremented but you did not update your countNode variable accordingly, and the index of each following child node decremented but you did not account for that when accessing Item[p].

The correct way to write such a loop would look more like this instead:

TTreeNode* ParentNode = TreeView->Selected;
int countNode = ParentNode->Count;
for(int p = 0; p < countNode; ++p)
{
    ParentNode->Item[0]->Delete();
}

Or:

TTreeNode* ParentNode = TreeView->Selected;
int countNode = ParentNode->Count;
while (countNode > 0)
{
    ParentNode->Item[0]->Delete();
    --countNode;
}

Or:

TTreeNode* ParentNode = TreeView->Selected;
int countNode = ParentNode->Count;
for(int p = countNode-1; p >= 0; --p)
{
    ParentNode->Item[p]->Delete();
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • I fixed my issue with decrement loop.. but in my case, it's more performant to avoid the loop and I use DeleteChildren. Thx Remy. Thx David. –  Mar 15 '15 at 13:47
  • Would you need to delete the children, or would `Delete()` do that? – David Heffernan Mar 16 '15 at 12:19