DWORD dwFunction = 0; //功能ID
HTREEITEM hItemLayer[5][2]; //用于保存当前正在操作的结点,用于回溯
int nIdCollection[5][2]; //保留父层结点的ID,用于识别下一个结点的父层所属
// 设置树根
hItemLayer[0][0] = m_treeOperatorPermission.InsertItem(_T("权限设置"),3,3);
m_treeOperatorPermission.SetItemData (hItemLayer[0][0] , dwFunction);
hItemLayer[0][1] = hItemLayer[0][0];
nIdCollection[0][0] = 0; //父层ID
nIdCollection[0][1] = 0; //当前层ID
int nCurParentLay = 0;
CADORecordset collection(&m_conn); //ADO对象,用于从数据库取出记录集
CString strSQLString("select id ,ParentId , Name , IdCode from tbl_function order by id , parentid");
if(collection.Open (strSQLString))
{
int nCount = collection.GetRecordCount ();
CString strFunctionName;
for(int i = 0;i <nCount;i ++)
{
//从数据库中取出结点数据
collection.GetFieldValue ("Name" , strFunctionName);
int nId;
int nParentId;
collection.GetFieldValue ("Id" , nId);
collection.GetFieldValue ("ParentId" , nParentId);
do
{
//判断其保留的父结点是否一致,用于判断是否从当前插入子结点,还是从父结点插入子结点
if(nParentId == nIdCollection[nCurParentLay][0])
{
//向父层插入子结点,并保留当前结点数据,用于回溯
hItemLayer[nCurParentLay][1] = m_treeOperatorPermission.InsertItem ((LPCTSTR)strFunctionName , 0 , 1 , hItemLayer[nCurParentLay][0]);
nIdCollection[nCurParentLay][1] = nId;
m_treeOperatorPermission.SetHalfChecked (hItemLayer[nCurParentLay][1]);
dwFunction = nId;
m_treeOperatorPermission.SetItemData (hItemLayer[nCurParentLay][1] , dwFunction);
}
else if(nParentId == nIdCollection[nCurParentLay][1])
{
//在当前层建立子层
hItemLayer[nCurParentLay + 1][1] = m_treeOperatorPermission.InsertItem ((LPCTSTR)strFunctionName , 0 , 1 , hItemLayer[nCurParentLay][1]);
hItemLayer[nCurParentLay + 1][0] = hItemLayer[nCurParentLay][1];
nIdCollection[nCurParentLay + 1][0] = nParentId;
nIdCollection[nCurParentLay + 1][1] = nId;
m_treeOperatorPermission.SetChecked (hItemLayer[nCurParentLay + 1][1] , FALSE);
dwFunction = nId;
m_treeOperatorPermission.SetItemData (hItemLayer[nCurParentLay + 1][1] , dwFunction);
nCurParentLay ++;
}
else
{
//回溯,用于找到相匹配的父结点,便于插入结点
nCurParentLay --;
continue;
}
break;
}while(true);
collection.MoveNext ();
}
m_treeOperatorPermission.Expand (hItemLayer[0][0] , TVE_EXPAND);
}
collection.Close ();
m_treeOperatorPermission.ClearALLCheck ();
return 0; |