MFC search tree view based on label (name)

So I recently came across a need to use a tree view in an MFC based application. I also found I needed to search that tree based on the label (text displayed to the user). After some research I found an old link here at MSDN. However the article is almost 6 years old. MFC has changed a bit since then. So I had to change the code a bit to use all the new MFC macros for tree view usage. All these macros are also defined as functions on the CTreeCtrl class but doing it this way allows you to traverse any tree you want instead of being tied to a single instance. You can read more about the macros and treeviews here.

All items are passed in except for MAXTEXTLEN which needs to be defined somewhere and included for reference. Mine is set to 100 since we can get fairly long long names in our application.

The function:
HTREEITEM GetItemByName(   HWND hWnd, 
HTREEITEM hItem,
LPCTSTR szItemName )
{
try
{
// If hItem is NULL, start search from root item.
if( hItem == NULL )
{
hItem = TreeView_GetRoot( hWnd );
}//end if

while( hItem != NULL )
{
TCHAR szBuffer[MAXTEXTLEN+1];
TV_ITEM item;

item.hItem = hItem;
item.mask = TVIF_TEXT | TVIF_CHILDREN;
item.pszText = szBuffer;
item.cchTextMax = MAXTEXTLEN;

TreeView_GetItem( hWnd, &item );

// Did we find it?
if( lstrcmp( item.pszText, szItemName ) == 0 )
{
return hItem;
}//end if

// Check whether we have child items.
if( item.cChildren )
{
// Recursively traverse child items.
HTREEITEM hItemFound, hItemChild;

hItemChild = TreeView_GetChild( hWnd, hItem );

hItemFound = GetItemByName( hWnd, hItemChild, szItemName );

// Did we find it?
if( hItemFound != NULL )
{
return hItemFound;
}//end if
}//end if

// Go to next sibling item.
hItem = TreeView_GetNextSibling( hWnd, hItem );

}//end while

// Not found.
return NULL;
}//end try
catch( CException* ex )
{
// TODO: add some logging here, etc
delete ex;
return NULL;
}//end catch
}


The usage:

HTREEITEM hItem = GetItemByName( aTreeHWND, NULL, _T("SOME NAME") );

if( hItem != NULL )
{
//TODO: SUCCESS!
}//end if
else
{
// TODO: FAILURE! :(
}//end else

Comments

Popular Posts