Expanding and Collapsing a Tree
Submitted by date of submission user level
Mahesh Chand Feb 02, 2001 Beginner
Ok, here is one more article on Tree activities.
In this sample code, I have considered all Tree Expand and Collapse possibilities such as Expanding/Collapsing all leaves, selected leaves and its children and only selected leaves.
Expand All
Expand All button expands every leaf of the tree until its last leaf.
Collapse All
Collapse All button collapses every leaf of the tree until its root leaf.
Expand Selected
This button expands current selected tree leaf and its children until last child.
Collapse All
This button collapses current selected tree leaf and its all children.
Expand
This button expands the current selected tree leaf only. This operation works for only one level.
Collapse
This button collapses the current selected tree leaf only. This operation works for only one level.
Here is the code. I believe every function is easy to understand here.
void CTreeDlgDlg::ExpandTree(HTREEITEM hRoot)
{
if( m_TreeCtrl.ItemHasChildren( hRoot) )
{
m_TreeCtrl.Expand( hRoot, TVE_EXPAND );
hRoot = m_TreeCtrl.GetChildItem( hRoot );//get the first child item of the selected children
if( hRoot )
{
do
{
ExpandTree( hRoot );//Call Recursively
}while( (hRoot = m_TreeCtrl.GetNextSiblingItem(hRoot) )!=NULL );
}
}
}
void CTreeDlgDlg::CollapseTree(HTREEITEM hRoot)
{
m_TreeCtrl.Expand( hRoot, TVE_COLLAPSE);
}
void CTreeDlgDlg::OnExpandSelected()
{
// Use GetSelectedItem to expand current selected item
ExpandTree( m_TreeCtrl.GetSelectedItem() );
}
void CTreeDlgDlg::OnColapseSelected()
{
// Use GetSelectedItem to expand current selected item
CollapseTree( m_TreeCtrl.GetSelectedItem() );
}
void CTreeDlgDlg::OnExpandOnly()
{
m_TreeCtrl.Expand( m_TreeCtrl.GetSelectedItem(), TVE_EXPAND );
}
void CTreeDlgDlg::OnColapseOnly()
{
m_TreeCtrl.Expand( m_TreeCtrl.GetSelectedItem(), TVE_COLLAPSE );
}
Attachments:
About the Author:
Mahesh is Admin and the founder of this site. He has been programming in VC++, Visual Basic, COM, ATL, Database Programming for 4 years. He can be reached at Mahesh. His background includes Master's in Computer Science and Applications and BS in Mathematics and Physics.