⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 addressbookview.cpp

📁 采用MFC DAO对象和接口编程技术实现一个地址簿数据库的管理器。
💻 CPP
字号:
// AddressBookView.cpp : implementation of the CAddressBookView class
//

#include "stdafx.h"
#include "AddressBook.h"

#include "AddressBookDoc.h"
#include "AddressBookView.h"
#include "Hints.h"
#include "DbChangeDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


/////////////////////////////////////////////////////////////////////////////
// CAddressBookView

IMPLEMENT_DYNCREATE(CAddressBookView, CListView)

BEGIN_MESSAGE_MAP(CAddressBookView, CListView)
	//{{AFX_MSG_MAP(CAddressBookView)
	ON_COMMAND(ID_OPEN_DABSE, OnOpenDabse)
	ON_UPDATE_COMMAND_UI(ID_OPEN_DABSE, OnUpdateOpenDabse)
	ON_COMMAND(ID_DELETE, OnDelete)
	ON_COMMAND(ID_NEWRECORD, OnNewrecord)
	ON_COMMAND(ID_REFRASH, OnRefrash)
	ON_UPDATE_COMMAND_UI(ID_REFRASH, OnUpdateRefrash)
	ON_UPDATE_COMMAND_UI(ID_DELETE, OnUpdateDelete)
	ON_COMMAND(ID_UPDATADB, OnUpdataDb)
	ON_UPDATE_COMMAND_UI(ID_UPDATADB, OnUpdateUpdataDb)
	ON_WM_LBUTTONDBLCLK()
	ON_WM_RBUTTONDOWN()
	ON_COMMAND(ID_POP_NEWRECORD, OnPopNewrecord)
	ON_COMMAND(ID_POP_UPDATE, OnPopUpdate)
	ON_COMMAND(ID_POP_DELETE, OnPopDelete)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////

UINT CAddressBookView::m_ColumnLabelID [NUM_COLUMNS] = 
{
	IDS_TABLE_HEAD_NAME,
	IDS_TABLE_HEAD_WPHONE,
	IDS_TABLE_HEAD_MPHONE,
	IDS_TABLE_HEAD_HPHONE,
	IDS_TABLE_HEAD_NOTE,
};

int CAddressBookView::m_ColumnFormat [NUM_COLUMNS] = 
{
	LVCFMT_LEFT, LVCFMT_LEFT, LVCFMT_LEFT, LVCFMT_LEFT
};

// CAddressBookView construction/destruction

CAddressBookView::CAddressBookView()
{
	// TODO: add construction code here
    
}

CAddressBookView::~CAddressBookView()
{
	if(m_pImageList!=NULL) delete m_pImageList;
}

BOOL CAddressBookView::PreCreateWindow(CREATESTRUCT& cs)
{
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs
	cs.style |= LVS_REPORT     |
			 LVS_SINGLESEL     |
			 LVS_SHOWSELALWAYS |
			 LVS_ICON          ;

	return CListView::PreCreateWindow(cs);
}

/////////////////////////////////////////////////////////////////////////////
// CAddressBookView drawing

void CAddressBookView::OnDraw(CDC* pDC)
{
	CAddressBookDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	// TODO: add draw code for native data here
}

void CAddressBookView::OnInitialUpdate()
{
	CListView::OnInitialUpdate();

	CListCtrl	&lc	= GetListCtrl();
	int Column;
	LV_COLUMN		LVColumn;		// column info of one column in list control

	CAddressBookDoc	*pDoc = (CAddressBookDoc*) GetDocument();
	
	DWORD dwStyle = ListView_GetExtendedListViewStyle(GetListCtrl());
	//Add the full row select and grid line style to the existing extended styles
	 dwStyle |= LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | /*LVS_EX_SUBITEMIMAGES |*/
							LVS_EX_HEADERDRAGDROP | LVS_EX_TRACKSELECT;
	ListView_SetExtendedListViewStyle (GetListCtrl(),dwStyle);


	lc.DeleteAllItems ();// regular cleanup

	m_pImageList = new CImageList();
	m_pImageList->Create(IDB_BITMAP1, 16, 1, RGB(0,0,0));
	GetListCtrl().SetImageList(m_pImageList, LVSIL_SMALL);
	
	//initialize the columns (insert columns)
	m_ColumnWidth [COL_NAME      ] = 100;
	m_ColumnWidth [COL_WPHONE    ] = 100;
	m_ColumnWidth [COL_MPHONE    ] = 100;
	m_ColumnWidth [COL_HPHONE    ] = 100;
	m_ColumnWidth [COL_NOTE      ] = 200;

	// set header and format for all visible columns
	LVColumn.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;

	{
		for (Column = 0; (Column < NUM_COLUMNS); Column++)
		{
			CString		HeaderString;
		
			// fill header data
			HeaderString.LoadString (m_ColumnLabelID[Column]);

			LVColumn.iSubItem	= Column;
			LVColumn.pszText	= (LPTSTR) (LPCTSTR) HeaderString;
			LVColumn.cx			= m_ColumnWidth [Column];
			LVColumn.fmt		= m_ColumnFormat [Column];
			lc.InsertColumn (Column, &LVColumn);
		}
	}

	CString strDbPath;	
	//SetDatabasePath("");
	strDbPath = GetDatabasePath();
	if(!strDbPath.IsEmpty())
	{
		pDoc->OnNewDocument(); pDoc->OnOpenDocument(strDbPath);
	}
	else 
	{
	   AfxMessageBox(_T("Please specify new database location"), MB_OK | MB_ICONEXCLAMATION);
	   CFileDialog dlg(TRUE,".mdb",		"Address Book.mdb",
		   OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
		   0,
		   this);
		if (dlg.DoModal() == IDOK) 
		{
			pDoc->OnNewDocument();
			SetDatabasePath(dlg.GetPathName());
			pDoc->OnOpenDocument(dlg.GetPathName());
			if (pDoc->m_bFileOpen) 
			pDoc->UpdateAllViews(NULL, HINT_DB_OPENED, NULL);
		}
	}

	SetFocus ();
	lc.SetItem (0, 0, LVIF_STATE, NULL, 0, LVIS_FOCUSED , LVIS_FOCUSED, 0);

	// TODO: You may populate your ListView with items by directly accessing
	//  its list control through a call to GetListCtrl().
}

/////////////////////////////////////////////////////////////////////////////
// CAddressBookView diagnostics

#ifdef _DEBUG
void CAddressBookView::AssertValid() const
{
	CListView::AssertValid();
}

void CAddressBookView::Dump(CDumpContext& dc) const
{
	CListView::Dump(dc);
}

CAddressBookDoc* CAddressBookView::GetDocument() // non-debug version is inline
{
	ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CAddressBookDoc)));
	return (CAddressBookDoc*)m_pDocument;
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CAddressBookView message handlers

void CAddressBookView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) 
{
	// TODO: Add your specialized code here and/or call the base class
	CListCtrl            &lc= GetListCtrl();
	CAddressBookDoc      *pDoc = (CAddressBookDoc*)GetDocument();
	CDaoRecordsetAccess  *pRS;
	pRS = new CDaoRecordsetAccess(pDoc->m_pDB);

	int i=0;
	switch(lHint)
	{
	case HINT_DB_OPENED:

		lc.DeleteAllItems();
		pRS->Open(dbOpenDynaset,pRS->GetDefaultSQL(),0);
		pRS->MoveFirst();
		while (!pRS->IsEOF())
		{
			int ItemIndex = lc.InsertItem(LVIF_TEXT | LVIF_PARAM, i, pRS->m_Name, 0, 0, 0, 0);
			int SubitemIndex = 1;
		
			lc.SetItem (ItemIndex, SubitemIndex++, LVIF_TEXT, pRS->m_Address,   0, 0, 0, 0);
			lc.SetItem (ItemIndex, SubitemIndex++, LVIF_TEXT, pRS->m_WorkPhone,     0, 0, 0, 0);
			lc.SetItem (ItemIndex, SubitemIndex++, LVIF_TEXT, pRS->m_HomePhone, 0, 0, 0, 0);
			lc.SetItem (ItemIndex, SubitemIndex++, LVIF_TEXT, pRS->m_Notes, 0, 0, 0, 0);
			pRS->MoveNext();
		}
		break;
	case HINT_NEW_RECORD:
		
		CDbChangeDlg dlg;
		CDaoRecordsetAccess *pRS1;

		pRS1 = new CDaoRecordsetAccess(pDoc->m_pDB);
		ASSERT(pRS1 != NULL);
		try
		{
			pRS1->Open();
			long numRec = pRS1->GetRecordCount();
		}
		catch (CDaoException* e)
		{
			delete pRS1;
			pRS1 = NULL;

			TCHAR szCause[255];
			CString strFormatted = _T("The data file could not be opened because of this error: \n");
			e->GetErrorMessage(szCause, 255);
			strFormatted += szCause;
			AfxMessageBox(strFormatted, MB_OK | MB_ICONEXCLAMATION);
			e->Delete();
			return ;
		}
		if(dlg.DoModal()==IDOK)
		{
			pRS1->AddNew();
			if(dlg.m_Name.IsEmpty())
			{
				AfxMessageBox("请嵌入姓名");return ;
			}
			pRS1->m_Address      =  dlg.m_Address;
			pRS1->m_EmailAddress =  dlg.m_Email;
			pRS1->m_HomePhone    =  dlg.m_hPhone;
			pRS1->m_MobilePhone  =  dlg.m_mPhone;
			pRS1->m_Notes        =  dlg.m_note;
			pRS1->m_WorkPhone    =  dlg.m_oPhone;
			pRS1->m_Name         =  dlg.m_Name;

			pRS1->Update();
			// refresh
			pRS1->Edit();
			pRS1->Update();
			pDoc->UpdateAllViews(NULL,HINT_DB_OPENED, NULL);
		}        
		delete 	pRS1;
		break;

	}
	delete pRS;	
}


void CAddressBookView::OnOpenDabse() 
{
	CAddressBookDoc	*pDoc = (CAddressBookDoc*) GetDocument();
    SetDatabasePath("");
	CFileDialog dlg(TRUE,".mdb",		"Address Book.mdb",
		   OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
		   0,
		   this);
    if (dlg.DoModal() == IDOK) 
	{
			pDoc->OnNewDocument();
			SetDatabasePath(dlg.GetPathName());
			pDoc->OnOpenDocument(dlg.GetPathName());
			if (pDoc->m_bFileOpen) 
			pDoc->UpdateAllViews(NULL, HINT_DB_OPENED, NULL);
	}
	
}

void CAddressBookView::OnUpdateOpenDabse(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	CAddressBookDoc	*pDoc = (CAddressBookDoc*) GetDocument();
	pCmdUI->Enable(!pDoc->m_bFileOpen);	
}

void CAddressBookView::OnDelete() 
{
    CListCtrl&	lc = GetListCtrl ();
	CAddressBookDoc	*pDoc = (CAddressBookDoc*) GetDocument();
	CDaoRecordsetAccess *pRS;

	int nItem = lc.GetNextItem (-1, LVNI_SELECTED);
	if(nItem==-1) { AfxMessageBox("清选择要删除的纪录");return;}

	// Verify deleting record with current Name
	CString str = lc.GetItemText(nItem, 0);
	if ( (AfxMessageBox("Delete the record with the following Name:  " +
		str, MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2)) == IDYES ) {
		CString sql(_T("Name = "));
		sql += "'";
		sql += str;
		sql += "'";
		pDoc->m_pSet->m_strFilter =sql;
		// requery the database
		pDoc->m_pSet->Requery();
		// delete the returned record
		pDoc->m_pSet->Delete();
		
		lc.DeleteItem(nItem);
	}
}

void CAddressBookView::OnNewrecord() 
{
	// TODO: Add your command handler code here
	CAddressBookDoc *pDoc = GetDocument ();
	if(pDoc->m_bFileOpen)
		pDoc->UpdateAllViews(NULL,HINT_NEW_RECORD,NULL);
	else 
		AfxMessageBox("请确定数据库的位置\n“文件”|“打开数据库”\n来定位数据库的位置");
}

void CAddressBookView::OnRefrash() 
{
	// TODO: Add your command handler code here
	CAddressBookDoc *pDoc = GetDocument ();
	pDoc->UpdateAllViews(NULL,HINT_DB_OPENED, NULL);	
}

void CAddressBookView::OnUpdateRefrash(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	CAddressBookDoc *pDoc = GetDocument ();
	pCmdUI->Enable(pDoc->m_bFileOpen);
}

void CAddressBookView::OnUpdateDelete(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	CListCtrl&	lc		= GetListCtrl();
	int nItem = lc.GetNextItem (-1, LVNI_SELECTED);
	if (nItem == -1) pCmdUI->Enable(0);
	
}


void CAddressBookView::OnUpdataDb() 
{
		// TODO: Add your command handler code here
	CAddressBookDoc *pDoc = GetDocument ();
	CListCtrl&	lc		  = GetListCtrl ();
    CDaoRecordsetAccess *pRS ;
	CDbChangeDlg dlg;


	pRS = new CDaoRecordsetAccess(pDoc->m_pDB);
	try
	{
		pRS->Open();
	}
	catch(CDaoException* e)
	{
		AfxMessageBox(e->m_pErrorInfo->m_strDescription);
		e->Delete();
	}

	if(pRS)
	{
		int index = lc.GetNextItem(-1,LVNI_SELECTED);
		if(index==-1) AfxMessageBox("清选择更新纪录");
		CString str = lc.GetItemText(index,0);
		CString sql(_T("[Name] = "));
		sql += "'";
		sql += str;
		sql += "'";
		pRS->m_strFilter =sql;
		pRS->Requery();
		
		//pRS->Edit();

		dlg.m_Address = pRS->m_Address;
		dlg.m_Email   = pRS->m_EmailAddress;
		dlg.m_hPhone  = pRS->m_HomePhone;
		dlg.m_mPhone  = pRS->m_MobilePhone;
		dlg.m_Name    = pRS->m_Name;
		dlg.m_note    = pRS->m_Notes;
		dlg.m_oPhone  = pRS->m_WorkPhone;
		
		if(dlg.DoModal()==IDOK) 
		{
			pRS->Edit();
		    pRS->m_Address      =  dlg.m_Address;
			pRS->m_EmailAddress =  dlg.m_Email;
			pRS->m_HomePhone    =  dlg.m_hPhone;
			pRS->m_MobilePhone  =  dlg.m_mPhone;
			pRS->m_Notes        =  dlg.m_note;
			pRS->m_WorkPhone    =  dlg.m_oPhone;
			pRS->m_Name         =  dlg.m_Name;
			pRS->Update();			         

			lc.DeleteItem(index);
			int ItemIndex = lc.InsertItem(LVIF_TEXT | LVIF_PARAM, index, pRS->m_Name, 0, 0, 0, 0);
			int SubitemIndex = 1;
		
			lc.SetItem (ItemIndex, SubitemIndex++, LVIF_TEXT, pRS->m_Address,   0, 0, 0, 0);
			lc.SetItem (ItemIndex, SubitemIndex++, LVIF_TEXT, pRS->m_WorkPhone,     0, 0, 0, 0);
			lc.SetItem (ItemIndex, SubitemIndex++, LVIF_TEXT, pRS->m_HomePhone, 0, 0, 0, 0);
			lc.SetItem (ItemIndex, SubitemIndex++, LVIF_TEXT, pRS->m_Notes, 0, 0, 0, 0);
			//SetFocus();
			lc.SetItemState (index, LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
		}
	}
	delete pRS;
	
}

void CAddressBookView::OnUpdateUpdataDb(CCmdUI* pCmdUI) 
{
    CListCtrl&	lc		= GetListCtrl();
	int nItem = lc.GetNextItem (-1, LVNI_SELECTED);
	if (nItem == -1) pCmdUI->Enable(0);	
	
}

void CAddressBookView::OnLButtonDblClk(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	CListCtrl&	lc		= GetListCtrl();
	int nItem = lc.GetNextItem (-1, LVNI_SELECTED);
	if (nItem != -1) OnUpdataDb();

	CListView::OnLButtonDblClk(nFlags, point);
}

void CAddressBookView::OnRButtonDown(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	CMenu PopMenu;
	CMenu *pMenu;
	CPoint pt;
	pt= point ;

	PopMenu.LoadMenu(IDR_POP_MENU);
			ClientToScreen (&pt);
			// show the menu (returns, when menu is closed again!)
			pMenu = PopMenu.GetSubMenu (0);
			pMenu->TrackPopupMenu (TPM_LEFTALIGN | TPM_RIGHTBUTTON,
				pt.x, pt.y, this);

	//CListView::OnRButtonDown(nFlags, pt);
}


void CAddressBookView::OnPopNewrecord() 
{
	// TODO: Add your command handler code here
	CAddressBookDoc *pDoc = GetDocument ();
	if(pDoc->m_bFileOpen)
		pDoc->UpdateAllViews(NULL,HINT_NEW_RECORD,NULL);
	else 
		AfxMessageBox("请确定数据库的位置");
}


void CAddressBookView::OnPopUpdate() 
{	
	OnUpdataDb();
}

void CAddressBookView::OnPopDelete() 
{
	// TODO: Add your command handler code here
    OnDelete();	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -