研究了好几天,今天终于弄好了,下面是代码
[dlg.cpp]
在初始函数OnInitDialog()中加
HICON hIcon[3];
HTREEITEM hRoot;
//加载三个图标
hIcon[0] = theApp.LoadIconW(IDI_ICON1);
hIcon[1] = theApp.LoadIconW(IDI_ICON3);
hIcon[2] = theApp.LoadIconW(IDI_ICON2);
m_imageList.Create(16, 16, ILC_COLOR16, 3, 3); for (int i=0;i<3;i++) { m_imageList.Add(hIcon[i]); } //绑定树控件与ImaageList m_webTree.SetImageList(&m_imageList, TVSIL_NORMAL); //初始化Ado环境 AfxOleInit(); hRoot = NULL; OpenConn(); //打开数据函数 LoadTreeCtrlData(hRoot,_T("0")); //递归加数据到树控件中 CloseConn(); //关闭数据库
//下面就是递归函数
void CMFCApp_CTreeCtrl_testDlg::LoadTreeCtrlData(HTREEITEM hItem,CString mid)
{
HTREEITEM temItem;
_RecordsetPtr m_pRecordset;
m_pRecordset.CreateInstance(__uuidof(Recordset));
try
{
CString sql;
sql.Format(_T("select * from mTable where pID='%s'"), mid);
m_pRecordset->Open((_variant_t)sql, m_pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText); //AfxMessageBox(_T("123")); } catch (_com_error e) { CString str; str.Format(_T("连接数据表失败:%s"), e.ErrorMessage()); AfxMessageBox(str); return; } _variant_t var; CString strTmp; while (!m_pRecordset->adoEOF) { var = m_pRecordset->GetCollect(_T("mName")); strTmp = (LPCTSTR)_bstr_t(var); temItem=m_webTree.InsertItem(strTmp, 1, 1, hItem, TVI_LAST); //把自己的mID存入到节点中,
//节点存放的是指针地址的数据,查了好几天百度才弄清.
var = m_pRecordset->GetCollect(_T("mID")); strTmp = (LPCTSTR)_bstr_t(var); CString* pStr = new CString; *pStr = strTmp; m_webTree.SetItemData(temItem,(DWORD)pStr); //递归加载子节点 LoadTreeCtrlData(temItem,strTmp); m_pRecordset->MoveNext(); }
}
//取出数据
CString strText;
HTREEITEM hItem = m_webTree.GetSelectedItem();
//strText = m_webTree.GetItemText(hItem);
CString str = (CString)m_webTree.GetItemData(hItem);
if(str!=NULL)
strText.Format(_T("%s"), str->GetString());
SetDlgItemText(IDC_ITEM_SET_EDIT,strText);
尽管磕磕绊绊的好几天,今天总算弄出效果了.
来源:https://www.cnblogs.com/greenleaf1976/p/12169365.html