通过树形控件中项的名称找到项(Finding an Item in a CTreeCtrl)
2014-03-29 12:17
645 查看
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.
[Update]
To search the entire tree you can use this helper function, which will work regardless how many roots the tree has.
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; }
相关文章推荐
- 通过ListItem找到相应控件
- [置顶] MFC树形控件CTreeCtrl使用方法、遍历、SetCheck无效、根据名称获取节点、获取选中节点等问题
- VC 控件的使用_1 树形控件(CTreeCtrl)使用简介
- Using An Item Template With An HTML Dropdown Menu Component In Angular 2 RC 3
- Finding sum of every combination of two numbers in an array in Ruby
- Winform中通过一个字符串定位到和字符串相等ID的控件(将字符串转换成相应的控件名称)
- VC6.0 MFC添加树形控件CTreeCtrl
- Delphi 使用 RTTI 动态通过名称调用函数和设置控件属性值
- 树形控件CTreeCtrl的使用详解(一)
- 树形控件(CTreeCtrl)简介
- 树形控件 CTreeCtrl CViewTree
- C#中通过反射方法获取控件类型和名称
- VC 树形控件(CTreeCtrl)的使用
- 控件隐藏后但可以通过JS找到
- MFC树控件CTreeCtrl中为每个item节点动态添加提示信息,并定时更新提示内容
- [MFC]CTreeView树形视图、CTreeCtrl树形控件
- vc++树形控件(CTreeCtrl)使用简介
- MFC树形控件(CTreeCtrl)用法(上)
- VC中树形控件(CTreeCtrl)的使用
- 树形控件(CTreeCtrl)使用简介