树型控件实现数据库的访问
作者:方锡武
本人意图将数据库中的内容加入树型控件中,通过建立数据库,再与树型控件相连,实现数据库的访问。查询结构清晰明了,操作方便。
现将其方法阐述如下:


工程名Ppp,视图类名为CPppView。

CShengSet

#include <afxwin.h // MFC core and standard components
#include <afxext.h // MFC extensions
#include <afxdisp.h // MFC Automation classes
#include <afxdao.h //加入行,实现本视图类对Access数据库的访问
#include <afxdtctl.h// MFC support for Internet Explorer 4 Common Controls
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h// MFC support for Windows Common Controls
#endif

#include"ShengSet.h"同时定义数据集类变量
public:
CShengSet *m_ShengSet;

#include"ShengSet.h"同时定义数据集类变量
public:
CShengSet m_ShengSet;


CFormView::OnInitialUpdate();
CPppDoc* pDoc = (CPppDoc*)GetDocument(); //得到指向文档类指针
m_ShengSet=&pDoc-m_ShengSet;//得到数据库指针

void CPppView::OnInitialUpdate()
{
CFormView::OnInitialUpdate();
CPppDoc* pDoc = (CPppDoc*)GetDocument();
m_ShengSet=&pDoc-m_ShengSet;
TV_INSERTSTRUCT tvinsert;
tvinsert.hParent = NULL;
tvinsert.item.mask = TVIF_TEXT;
tvinsert.item.pszText = "全国";
HTREEITEM hDad = m_treectrl.InsertItem(&tvinsert);
if (m_ShengSet-IsOpen())
m_ShengSet-Close();
m_ShengSet-Open();
m_ShengSet-MoveFirst();
CString c1;
char buff[80];
while(!m_ShengSet-IsEOF())
{
c1=m_ShengSet-m_column1;
wsprintf(buff,"%s",c1);
tvinsert.item.pszText = buff;
tvinsert.hParent = hDad;
m_treectrl.InsertItem(&tvinsert);
m_ShengSet-MoveNext();
}
}
最终结果如图1左边窗口所示:

#include"PppDoc.h"
#include "ShengSet.h"

public:
CSplitterWnd m_wndSpMain;
运用向导加入OnCreateClient()函数和以下代码实现数据记录显示BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)
{
if (!m_wndSpMain.CreateStatic(this, 1, 2))
{
TRACE0("Failed to create splitter window\n");
return FALSE;
}
if (!m_wndSpMain.CreateView(0, 0, RUNTIME_CLASS(CPppView),
CSize(180, 200), pContext))
{
TRACE0("Failed to create left pane view\n");
return FALSE;
}
if (!m_wndSpMain.CreateView(0, 1,
RUNTIME_CLASS(CShengView), CSize(100,100), pContext))
{
TRACE0("Failed to create right pane frame\n");
return FALSE;
}
return TRUE;
}
该代码实现本框架两个窗口的显示。至此本程序达到如下图效果:

图一

.h 文件中加入
public:
CString Name;

void CIdView::OnSelchangedTree1(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
CTreeCtrl* pTree2 = (CTreeCtrl*) GetDlgItem(IDC_TREE1);
HTREEITEM hSelected = pNMTreeView-itemNew.hItem;
CPppDoc* pDoc = (CPppDoc*)GetDocument();
CString hParentName;
HTREEITEM hParent=pTree2-GetParentItem(hSelected);
if(hSelected!=NULL)
{
pDoc-Name=pTree2-GetItemText(hSelected);
}
*pResult = 0;
}

void CShengView::OnTimer(UINT nIDEvent)
{
CPppDoc* pDoc = (CPppDoc*)GetDocument();
if (m_pSet-IsOpen())
{
char filter[60];
wsprintf(filter,"[省].省名称=''%s''",pDoc-Name);
m_pSet-m_strFilter=filter;
m_pSet-Requery();
UpdateData(FALSE);
}
}

void CShengView::OnInitialUpdate()
{
CRecordView::OnInitialUpdate();
SetTimer(1,10,NULL);
}
总结:本方法以树型控件形式实现可视化数据库浏览,编程实现简单,实际操作方便。