Page 1 of 1

Treeview Branch Item Recursion Loop

Posted: 10 Sep 2017, 06:06
by icuurd12b42
This recursive function iterates through the entire branch structure of the specified treeview item and fill up an array with all items contained under it which you can then loop through to perform actions on all the items in that branch

The array will not contain the start treeview item, only it's children items and sub branches will be in the array.

The array is superfluous as you could effect the items while in the recursive function, but this allows using the function in a generic way...

Code: Select all

global RecurseItemsCount := 0
global RecurseItems := Object()

RecurseTreeBranch(TVItem)
{
	ThisTVItem:=TV_GetChild(TVItem) ;start with the first child of this item
	if(ThisTVItem)
	{
		Loop ;loop through siblings of that child
		{
			;Set the array with the item
			RecurseItemsCount := RecurseItemsCount + 1
			RecurseItems[RecurseItemsCount] := ThisTVItem
			;TV_GetText(ItemText, ThisTVItem)
			;MsgBox Text is "%ItemText%".
			;does this item have any children?
			if(TV_GetChild(ThisTVItem))
			{
				;recurse
				RecurseTreeBranch(ThisTVItem)
			}
			;next sibling
			ThisTVItem := TV_GetNext(ThisTVItem) 
			if (not ThisTVItem)  ; No more items in this branch.
			{	
				break
			}
		}
	}
}

ExampleUseExpandAll(StartItem)	
{
	RecurseItemsCount := 0 ;reset the array count
	RecurseTreeBranch(StartItem) ;call the function
	;Loop the array
	Count := RecurseItemsCount
	if(Count>0)
	{
		Loop %Count%
		{
			ThisTVItem := RecurseItems[A_Index]
			TV_Modify(ThisTVItem, "+Expand")
			;TV_GetText(ItemText, ThisTVItem)
    			;MsgBox Text is "%ItemText%".
		}
	}
	TV_Modify(StartItem, "+Expand")
}

Re: Treeview Branch Item Recursion Loop

Posted: 10 Sep 2017, 06:49
by Guest
Thanks for sharing.
An example would be nice.
Also, when it comes to Listviews and Treeviews, it's better to use LVM and TVM.

Re: Treeview Branch Item Recursion Loop

Posted: 10 Sep 2017, 12:15
by icuurd12b42
Guest wrote:Thanks for sharing.
An example would be nice.
Ok, not sure why you would ask as it's in there already

Also, when it comes to Listviews and Treeviews, it's better to use LVM and TVM.
Not sure what you imply here... I'll assume you mean TVM_GETNEXTITEM via SendMessage() to get the exact same data required for traversing the treeview items? Why is that better? The TV_GetChild and TV_GetNext already give that information.

Re: Treeview Branch Item Recursion Loop

Posted: 31 Mar 2021, 12:07
by jasc2v8
Nice code, thank you!

I've modified and included in my library with examples

https://www.autohotkey.com/boards/viewtopic.php?f=6&t=88815