通过树形控件中项的名称找到项(Finding an Item in a CTreeCtrl)

If you want to find an item in a tree control (CTreeCtrl from MFC) by its name you need a recursive function. Below is a function that does that. How does it work: you pass the text of the item to search, the tree reference and an item in the tree. The function will search through the sub-tree of that item for a match. If it finds it, it returns the tree item, otherwise NULL. To search the entire tree, pass the root of the tree. If your tree has more than just one root and you want to search the entire tree, you’d have to call it once for each root item.

// name - the name of the item that is searched for
// tree - a reference to the tree control
// hRoot - the handle to the item where the search begins
HTREEITEM FindItem(const CString& name, CTreeCtrl& tree, HTREEITEM hRoot)
{
   // check whether the current item is the searched one
   CString text = tree.GetItemText(hRoot);
   if (text.Compare(name) == 0)
      return hRoot; 
 
   // get a handle to the first child item
   HTREEITEM hSub = tree.GetChildItem(hRoot);
   // iterate as long a new item is found
   while (hSub)
   {
      // check the children of the current item
      HTREEITEM hFound = FindItem(name, tree, hSub);
      if (hFound)
         return hFound; 
 
      // get the next sibling of the current item
      hSub = tree.GetNextSiblingItem(hSub);
   } 
 
   // return NULL if nothing was found
   return NULL;
}

[Update]
To search the entire tree you can use this helper function, which will work regardless how many roots the tree has.

HTREEITEM CTreeDemoDlg::FindItem(const CString& name, CTreeCtrl& tree)
{
   HTREEITEM root = m_tree.GetRootItem();//m_tree是成员变量,即当前要搜索的树形控件
   while(root != NULL)
   {
      HTREEITEM hFound = FindItem(name, tree, root);
      if (hFound)
         return hFound; 
 
      root = tree.GetNextSiblingItem(root);
   }
 
   return NULL;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值