CTreeCtrl利用TV_ITEM插入节点与遍历节点

插入树节点

TV_ITEM tvItem;
tvItem.mask = TVIF_TEXT | TVIF_PARAM | TVIF_IMAGE | TVIF_HANDLE | TVIF_SELECTEDIMAGE | TVIS_SELECTED | TVIS_EXPANDED; 
CString TmpStr = "文本内容"
tvItem.pszText =(LPWSTR)(LPCTSTR)TmpStr;
tvItem.cchTextMax = MAX_PATH;
tvItem.lParam  =nID;  // 额外参数
tvItem.iImage =0;      // 未被选中时显示的图片
tvItem.iSelectedImage = 1;   // 选中时显示的图片


TV_INSERTSTRUCT tvInsert;
tvInsert.hParent = ParentNode;  // 确定父节点
tvInsert.hInsertAfter = TVI_LAST;
tvInsert.item = tvItem;       

HTREEITEM RetItm = m_tree.InsertItem(&tvInsert);

 

 

// 遍历树节点,代码为获得树控件节点的item.lparam

GetChildItemID(CTreeCtrl* pCtrlTree,HTREEITEM& hNode)
{
    TVITEM item;
    item.mask = TVIF_PARAM;

    if (pCtrlTree->ItemHasChildren(hNode))//是否有孩子节点
    {
        HTREEITEM hNextItem;
        HTREEITEM hChildItem = pCtrlTree->GetChildItem(hNode); 

        while (hChildItem != NULL)
        {
            hNextItem = pCtrlTree->GetNextItem(hChildItem, TVGN_NEXT);
            item.hItem = hChildItem;
            pCtrlTree->GetItem(&item);
            //得到item.lParam
            GetChildOrgID(pCtrlTree,hChildItem);//遍历
            hChildItem = hNextItem;
        }

    }

}

 

 

 

// 遍历添加节点


AddTreeItem(CTreeCtrl* pCtrlTree,HTREEITEM& ParentNode,  const  int nParentID)
{
    int nCount=m_OrgArr.size();//m_OrgArr是一个vector类型的数组
    HTREEITEM RetItm;

    for(int i=0;i    {
        XXX*    pObj    =    (XXX*)(int)m_OrgArr.at(i);

        if(pObj->nParentID==nParentID)//满足要求就插入了
        {
            TV_ITEM tvItem;
            tvItem.mask = TVIF_TEXT | TVIF_PARAM | TVIF_IMAGE | TVIF_HANDLE | TVIF_SELECTEDIMAGE | TVIS_SELECTED | TVIS_EXPANDED; 
            CString TmpStr = pObj->sTest; //(LPSTR)
            tvItem.pszText =(LPWSTR)(LPCTSTR)TmpStr;
            tvItem.cchTextMax = MAX_PATH;
            tvItem.lParam  =pObj->nID;
            tvItem.iImage =0;
            tvItem.iSelectedImage = 1;
            
            TV_INSERTSTRUCT tvInsert;
            tvInsert.hParent = ParentNode;
            tvInsert.hInsertAfter = TVI_LAST;
            tvInsert.item = tvItem;

            HTREEITEM RetItm = pCtrlTree->InsertItem(&tvInsert);
             AddTreeItem(pCtrlTree,RetItm,pObj->nID);
        }

    }


}

你可能感兴趣的:(C/C++,TV_ITEM,CTreeCtrl,添加节点,遍历节点)