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

📄 daoaccessdlg.cpp

📁 VisualC高级编程技术精粹.rar
💻 CPP
字号:
// DAOAccessDlg.cpp : implementation file
//

#include "stdafx.h"
#include "DAOAccess.h"
#include "DAOAccessDlg.h"

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

CDaoDatabase db;				//数据库
CDaoRecordset RecSet(&db);		//记录集
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDAOAccessDlg dialog

CDAOAccessDlg::CDAOAccessDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CDAOAccessDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDAOAccessDlg)
	m_csName = _T("");
	m_csPosition = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

	m_csClass = _T("");
	m_csDatebaseFile = _T("");
	m_bIsCreateDB = FALSE;
	m_bIsOpenDB = FALSE;
	m_bIsOpenDSN = FALSE;
}

void CDAOAccessDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDAOAccessDlg)
	DDX_Control(pDX, IDC_INFO_LIST, m_listctrlInfo);
	DDX_Control(pDX, IDC_COMBO_CLASS, m_comboClass);
	DDX_Text(pDX, IDC_EDIT_NAME, m_csName);
	DDX_Text(pDX, IDC_EDIT_POSITION, m_csPosition);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CDAOAccessDlg, CDialog)
	//{{AFX_MSG_MAP(CDAOAccessDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_ADD, OnButtonAdd)
	ON_BN_CLICKED(IDC_BUTTON_DELETE, OnButtonDelete)
	ON_BN_CLICKED(IDC_BUTTON_QUERY, OnButtonQuery)
	ON_BN_CLICKED(IDC_BUTTON_QUIT, OnButtonQuit)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDAOAccessDlg message handlers

BOOL CDAOAccessDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.
	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	// 初始化下拉列表框
	m_comboClass.AddString(_T("一班"));
	m_comboClass.AddString(_T("二班"));
	m_comboClass.AddString(_T("三班"));
	m_comboClass.AddString(_T("四班"));
	m_comboClass.AddString(_T("五班"));
	m_comboClass.SetCurSel(0);

	// 初始化ListCtrl
	m_listctrlInfo.SetExtendedStyle( LVS_EX_GRIDLINES );
	m_listctrlInfo.SetExtendedStyle( m_listctrlInfo.GetExtendedStyle() | 
		                             LVS_EX_FULLROWSELECT );
	m_listctrlInfo.InsertColumn(0, "姓名", LVCFMT_CENTER, 170);
	m_listctrlInfo.InsertColumn(1, "班级", LVCFMT_CENTER, 140);
	m_listctrlInfo.InsertColumn(2, "名次", LVCFMT_CENTER, 135);
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CDAOAccessDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CDAOAccessDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CDAOAccessDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CDAOAccessDlg::OnButtonAdd() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
	
	// 判决姓名是否为空
	if (m_csName.IsEmpty())
	{
		GetDlgItem(IDC_STATIC_INFO)->SetWindowText(_T("姓名不能为空!"));
		return;
	}
	
	// 判决名次是否为空
	if (m_csPosition.IsEmpty())
	{
		GetDlgItem(IDC_STATIC_INFO)->SetWindowText(_T("名次不能为空!"));
		return;
	}

	// 获取班级
	int nCurSelClass = m_comboClass.GetCurSel();
    m_comboClass.GetLBText(nCurSelClass, m_csClass);

	// 获取数据库文件
	m_csDatebaseFile = GetDatabaseFile();
	
	CFileFind  fFind;
	m_bIsCreateDB = fFind.FindFile(m_csDatebaseFile);
	fFind.Close ();

    // 是否已经存在StudentInfo.mdb文件,没有则创建它
	if (!m_bIsCreateDB)
	{
		db.Create(m_csDatebaseFile);
		m_bIsCreateDB = TRUE;
		m_bIsOpenDB = TRUE;

		CString SqlCmd = "CREATE TABLE PositionTable(姓名 VARCHAR(20),班级 VARCHAR(8),名次 VARCHAR(8));";
		db.Execute(SqlCmd);
	
		InsertData();
	}
	else
	{
		InsertData();
	}	
}

void CDAOAccessDlg::InsertData()
{
	// 打开已创建的数据表
	if (!m_bIsOpenDB)
	{
		db.Open(m_csDatebaseFile,FALSE,FALSE,"");		
	}

	if (!m_bIsOpenDSN)
	{
		RecSet.Open(AFX_DAO_USE_DEFAULT_TYPE,"SELECT * FROM PositionTable", 0);
		m_bIsOpenDSN = TRUE;
	}

	// 加入记录,用SQL语句
	//db.Execute("INSERT INTO PositionTable (姓名,班级,名次) VALUES ('"+m_csName+"','"+m_csClass+"','"+m_csPosition+"')");
	
	// 加入记录,用DAO函数
	RecSet.AddNew();
	RecSet.SetFieldValue("姓名",(LPCTSTR)m_csName);
	RecSet.SetFieldValue("班级",(LPCTSTR)m_csClass);
	RecSet.SetFieldValue("名次",(LPCTSTR)m_csPosition);
	RecSet.Update();		

	GetDlgItem(IDC_STATIC_INFO)->SetWindowText(_T("添加数据成功!"));

	// 清空列表
	ClearContent();
}

void CDAOAccessDlg::OnButtonDelete() 
{
	// TODO: Add your control notification handler code here
	// 判断列表是否为空
	if (m_listctrlInfo.GetItemCount() == 0)
	{
		GetDlgItem(IDC_STATIC_INFO)->SetWindowText(_T("当前列表中没有数据!"));
		return;
	}
	// 取得第一条记录的位置
	POSITION pos = m_listctrlInfo.GetFirstSelectedItemPosition();
	if( NULL == pos )
	{		
		// 若没有选择记录,则给出提示
		GetDlgItem(IDC_STATIC_INFO)->SetWindowText(_T("你还没有选择一条记录,请选择!"));
		return;
	}		
	
	int nIndexInFieldList;
	while(pos)
	{ 	
		// 取得被选择记录的索引
		nIndexInFieldList = m_listctrlInfo.GetNextSelectedItem(pos);

		// 高亮被的选择记录
		m_listctrlInfo.SetFocus();

		// 从文件中把当前行记录删除
		// 获取数据库文件
		m_csDatebaseFile = GetDatabaseFile();

		// 判断数据库是否已经打开
		if (!m_bIsOpenDB)
		{
			db.Open(m_csDatebaseFile);	

			// 判断数据集是否已经打开
			if (!m_bIsOpenDSN)
			{
				RecSet.Open(AFX_DAO_USE_DEFAULT_TYPE,"SELECT * FROM PositionTable",NULL);
			}
		}
		
		m_nTotal = m_listctrlInfo.GetItemCount();
		m_nCurrentIndex = ConvertIndex(nIndexInFieldList,m_nTotal - 1);
		RecSet.MoveFirst();
		RecSet.Move(long(m_nCurrentIndex));
		RecSet.Delete();

		ClearContent();
		
		// 删除被的选择记录
		m_listctrlInfo.DeleteItem( nIndexInFieldList );

		// 显示删除数据成功的信息
		GetDlgItem(IDC_STATIC_INFO)->SetWindowText(_T("删除数据成功!"));

		// 再次取得第一条记录的位置
		POSITION pos = m_listctrlInfo.GetFirstSelectedItemPosition();
		UINT flag = LVIS_SELECTED|LVIS_FOCUSED;
		m_listctrlInfo.SetItemState( nIndexInFieldList, flag, flag );			
	}					
}

void CDAOAccessDlg::OnButtonQuery() 
{
	// TODO: Add your control notification handler code here
	COleVariant var; // 字段类型
	var.ChangeType(VT_BSTR, NULL);
	CString csName = _T("");
	CString csClass = _T("");
	CString csPosition = _T("");
	CString csFile = _T(""); 

	// 清空列表
	if (m_listctrlInfo.GetItemCount() !=0)
	{
		m_listctrlInfo.DeleteAllItems();
	}

	// 获取数据库文件
	m_csDatebaseFile = GetDatabaseFile();

	// 判断数据库是否已经打开
	if (!m_bIsOpenDB)
	{
		db.Open(m_csDatebaseFile);
		m_bIsOpenDB = TRUE;

		// 判断数据集是否已经打开
		if (!m_bIsOpenDSN)
		{
			RecSet.Open(AFX_DAO_USE_DEFAULT_TYPE,"SELECT * FROM PositionTable",NULL);
			m_bIsOpenDSN = TRUE;
		}
	}	

	if (!RecSet.IsBOF())
	{
		RecSet.MoveFirst();
	}
	else
	{
		GetDlgItem(IDC_STATIC_INFO)->SetWindowText(_T("数据库表中没有数据!"));
		return;
	}

	while (!RecSet.IsEOF())	// 有没有到表结尾
	{
		RecSet.GetFieldValue("姓名",var);
		csName = (LPCSTR)var.pbstrVal;

		RecSet.GetFieldValue("班级",var);
		csClass = (LPCSTR)var.pbstrVal;

		RecSet.GetFieldValue("名次",var);
		csPosition = (LPCSTR)var.pbstrVal;

		// 添加数据到列表
		m_listctrlInfo.InsertItem(0, _T(""));
		m_listctrlInfo.SetItemText(0, 0, csName);
		m_listctrlInfo.SetItemText(0, 1, csClass);
		m_listctrlInfo.SetItemText(0, 2, csPosition);

		RecSet.MoveNext();
	}

	// 显示查询数据成功的信息
	GetDlgItem(IDC_STATIC_INFO)->SetWindowText(_T("查询数据成功!"));
}

void CDAOAccessDlg::OnButtonQuit() 
{
	// TODO: Add your control notification handler code here
	if (RecSet.IsOpen())
	{
		RecSet.Close();
	}

	if (db.IsOpen())
	{
		db.Close();
	}

	CDialog::OnCancel();
}

int CDAOAccessDlg::ConvertIndex(int nCurrent,int nTotal)
{
	int nTemp = -1;

	for (int i = nCurrent; i <= nTotal; i++)
	{
		nTemp = nCurrent;
		nCurrent = nTotal - i;
		nTotal = nTemp;
	}

	return nCurrent;
}

void CDAOAccessDlg::ClearContent()
{
	m_csName = _T("");
	m_csPosition = _T("");
	UpdateData(FALSE);
}

CString CDAOAccessDlg::GetDatabaseFile()
{
	// 获取主程序所在路径
	CString csPath= _T("");
	GetModuleFileName(NULL,csPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH);
	csPath.ReleaseBuffer ();
    int nPos = -1;
	nPos = csPath.ReverseFind ('\\');
	csPath = csPath.Left (nPos);
	CString csDatebaseFile = csPath + _T("\\StudentInfo.mdb");

	return csDatebaseFile;
}

⌨️ 快捷键说明

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