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

📄 demo5dlg.cpp

📁 Viaual C++实战演练一书的源代码,对于C++程序员有实际的借鉴意义.
💻 CPP
字号:
// Demo5Dlg.cpp : implementation file
//

#include "stdafx.h"
#include "Demo5.h"
#include "Demo5Dlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// 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()

/////////////////////////////////////////////////////////////////////////////
// CDemo5Dlg dialog

CDemo5Dlg::CDemo5Dlg(CWnd* pParent /*=NULL*/)
	: CDialog(CDemo5Dlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDemo5Dlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_piConnection = NULL;
	m_piRecordset = NULL;
	m_nModified = 0;
	m_bEditable = false;
}

void CDemo5Dlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDemo5Dlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
	DDX_GridControl(pDX, IDC_GRID, m_Grid);
}

BEGIN_MESSAGE_MAP(CDemo5Dlg, CDialog)
	//{{AFX_MSG_MAP(CDemo5Dlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_TABLE, OnTable)
	ON_BN_CLICKED(IDC_USRTABLE, OnUsrtable)
	ON_BN_CLICKED(IDC_SELECT, OnSelect)
	ON_BN_CLICKED(IDC_ADD, OnAdd)
	ON_BN_CLICKED(IDC_DELETE, OnDelete)
	ON_BN_CLICKED(IDC_MODIFY, OnModify)
	//}}AFX_MSG_MAP
	ON_NOTIFY(GVN_SELCHANGED, IDC_GRID, OnSelChanged)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDemo5Dlg message handlers

BOOL CDemo5Dlg::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_Grid.SetEditable(false);
	m_Grid.SetListMode(FALSE);
	m_Grid.SetFixedTextColor(RGB(0, 0, 0xff));
	m_Grid.EnableDragAndDrop(TRUE);
	m_Grid.SetTextBkColor(RGB(0xFF, 0xFF, 0xE0));

	m_Grid.SetFixedRowCount(1);
	m_Grid.SetFixedColumnCount(1);
	m_Grid.SetItemText(0,0, _T("字段"));
	
	HRESULT hr;
	hr = m_piConnection.CreateInstance("ADODB.Connection");//创建连接对象实例

	COleVariant	vNull, vValue, vValue1;
	vNull.vt = VT_ERROR;
	vNull.scode = DISP_E_PARAMNOTFOUND;

	hr = m_piConnection->Open("Demo", "admin", "",adOpenUnspecified);//打开数据库连接
	hr = m_piRecordset.CreateInstance("ADODB.Recordset");//创建纪录集对象实例
	hr = m_piRecordset->putref_ActiveConnection(m_piConnection);//设置连接对象

	//hr = m_piRecordset->Open("select * from 船舶性能表", vNull, adOpenKeyset, adLockOptimistic, adCmdUnknown); //打开纪录集
	hr = m_piRecordset->Open("select * from 船舶性能表", vNull, adOpenDynamic, adLockOptimistic, adCmdText); //打开纪录集

	m_nFieldCount = m_piRecordset->Fields->GetCount();//获得纪录集总列数

	m_pFieldsType = new UINT[m_nFieldCount];//申请数组内存空间
	//if (!m_pFields)
	//	_com_issue_error(E_OUTOFMEMORY);
	memset(m_pFieldsType, 0, m_nFieldCount * sizeof(UINT));

	long lFld;
	for (lFld = 0; lFld < m_nFieldCount; lFld++)
	{
		m_pFieldsType[lFld] = m_piRecordset->Fields->Item[lFld]->Type;
		switch(m_pFieldsType[lFld])
		{//转换数据类型定义
		case adVarWChar:
		case adVarChar:
		case adLongVarChar:
			m_pFieldsType[lFld] = (DataTypeEnum)VT_BSTR;
			break;
		case adDBDate:
		case adDBTime:
		case adDBTimeStamp:
			m_pFieldsType[lFld] = (DataTypeEnum)VT_DATE;
			break;
		}
	}

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CDemo5Dlg::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 CDemo5Dlg::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 CDemo5Dlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CDemo5Dlg::OnDestroy() 
{
	CDialog::OnDestroy();
	
	// TODO: Add your message handler code here
	if(m_piRecordset)
		m_piRecordset->Close();
	if(m_piConnection)
		m_piConnection->Close();
	delete[] m_pFieldsType;//删除动态数组
}

void CDemo5Dlg::OnSelChanged(NMHDR* pNMHDR, LRESULT* pResult)
{//处理MFCGridCtrl对象事件
	if(!m_nModified)
	{
		NM_GRIDVIEW *nmgv = (NM_GRIDVIEW *)pNMHDR;
		//nmgv->iColumn 为栅格列标号
		//nmgv->iRow 为栅格行编号
		m_nSelectedRow = nmgv->iRow;
	}
}

void CDemo5Dlg::SetButtonCtrl()
{
	CButton* button;

	if(m_nModified)
	{
		button = (CButton*)GetDlgItem(IDC_SELECT);
		button->SetWindowText("确定");
		button = (CButton*)GetDlgItem(IDC_ADD);
		button->SetWindowText("取消");
		button = (CButton*)GetDlgItem(IDC_DELETE);
		button->ModifyStyle(0, WS_DISABLED);
		button = (CButton*)GetDlgItem(IDC_MODIFY);
		button->ModifyStyle(0, WS_DISABLED);
		button = (CButton*)GetDlgItem(IDC_TABLE);
		button->ModifyStyle(0, WS_DISABLED);
		button = (CButton*)GetDlgItem(IDC_USRTABLE);
		button->ModifyStyle(0, WS_DISABLED);
		button = (CButton*)GetDlgItem(IDCANCEL);
		button->ModifyStyle(0, WS_DISABLED);
	}
	else
	{
		button = (CButton*)GetDlgItem(IDC_SELECT);
		button->SetWindowText("查询");
		button = (CButton*)GetDlgItem(IDC_ADD);
		button->SetWindowText("增加");
		button = (CButton*)GetDlgItem(IDC_DELETE);
		button->ModifyStyle(WS_DISABLED, 0);
		button = (CButton*)GetDlgItem(IDC_MODIFY);
		button->ModifyStyle(WS_DISABLED, 0);
		button = (CButton*)GetDlgItem(IDC_TABLE);
		button->ModifyStyle(WS_DISABLED, 0);
		button = (CButton*)GetDlgItem(IDC_USRTABLE);
		button->ModifyStyle(WS_DISABLED, 0);
		button = (CButton*)GetDlgItem(IDCANCEL);
		button->ModifyStyle(WS_DISABLED, 0);
	}
	Invalidate(false);
}

void CDemo5Dlg::OnTable() 
{
	// TODO: Add your control notification handler code here
	int lNumFields, lNumRecord, i;
	long lFld;
	CString cName;
	COleVariant	vValue;
	_RecordsetPtr pRecordset;

	m_bEditable = false;

	pRecordset = m_piConnection->OpenSchema(adSchemaTables);
	lNumFields = pRecordset->Fields->GetCount();//获得纪录集总列数

	m_Grid.SetColumnCount(lNumFields+1);
	pRecordset->MoveLast();
	lNumRecord = pRecordset->RecordCount;
	m_Grid.SetRowCount(lNumRecord+1);
	pRecordset->MoveFirst();

	for(lFld = 0; lFld < lNumFields; lFld++)
	{//显示字段名
		cName = (PCSTR)pRecordset->Fields->Item[lFld]->Name;//字段名
		m_Grid.SetItemText(0,lFld+1, cName);
	}
	for(i = 0; i < lNumRecord ; i++) 
	{//显示数据
		for (lFld = 0; lFld < lNumFields; lFld++)
		{
			vValue = pRecordset->Fields->Item[lFld]->Value;//当前记录字段数据(可用MoveNext等命令移动)
			if(vValue.vt > 1)
			{//数据非空
				cName = vValue.bstrVal;
				m_Grid.SetItemText(i+1, lFld+1, cName);//printf(a1.bstrVal);
			}
			else
				m_Grid.SetItemText(i+1, lFld+1, "");
		}
		cName.Format("记录%i:", i+1);
		m_Grid.SetItemText(i+1, 0, cName);
		pRecordset->MoveNext();
	}
	pRecordset->Close();
	m_Grid.Invalidate();
}

void CDemo5Dlg::OnUsrtable() 
{
	// TODO: Add your control notification handler code here
	int lNumFields, i=0;
	long lFld;
	CString cName;
	COleVariant	vValue;
	_RecordsetPtr pRecordset;

	m_bEditable = false;

	pRecordset = m_piConnection->OpenSchema(adSchemaTables);
	lNumFields = pRecordset->Fields->GetCount();//获得纪录集总列数

	m_Grid.SetColumnCount(lNumFields+1);
	m_Grid.SetRowCount(1);

	for(lFld = 0; lFld < lNumFields; lFld++)
	{//显示字段名
		cName = (PCSTR)pRecordset->Fields->Item[lFld]->Name;//字段名
		m_Grid.SetItemText(0, lFld+1, cName);
	}
	while(!pRecordset->EndOfFile) 
	{//显示数据
		vValue = pRecordset->Fields->Item["TABLE_TYPE"]->Value;
		cName = vValue.bstrVal;
		if(cName == "TABLE")
		{
			i = m_Grid.GetRowCount();
			cName.Format("记录%i:", i);
			m_Grid.InsertRow(cName, -1);
			for (lFld = 0; lFld < lNumFields; lFld++)
			{
				vValue = pRecordset->Fields->Item[lFld]->Value;//当前记录字段数据(可用MoveNext等命令移动)
				if(vValue.vt != 1)
				{//数据非空
					cName = vValue.bstrVal;
					m_Grid.SetItemText(i, lFld+1, cName);//printf(a1.bstrVal);
				}
			}
		}
		pRecordset->MoveNext();
	}
	pRecordset->Close();
	m_Grid.Invalidate();
}

void CDemo5Dlg::OnSelect() 
{
	// TODO: Add your control notification handler code here
	long lFld, i;
	CString cName;
	COleVariant	vNull, vValue, vValue1;

	if(m_nModified)
	{
		if(m_nModified == 1)
			m_piRecordset->AddNew();
		for(i=0; i< m_nFieldCount; i++)
		{
			vValue = m_Grid.GetItemText(m_nSelectedRow, i+1);
			if( m_pFieldsType[i] == VT_BSTR && strlen((char*)vValue.bstrVal)>0 )
				m_piRecordset->Fields->Item[i]->Value = vValue;
			else if( m_pFieldsType[i] != VT_BSTR && VariantChangeType(&vValue1, &vValue, 0, m_pFieldsType[i]) == S_OK )
				m_piRecordset->Fields->Item[i]->Value = vValue1;
		}
		m_piRecordset->Update();
		m_Grid.SetEditable(false);
		m_nModified = 0;
		SetButtonCtrl();
	}

	m_bEditable = true;
	m_nSelectedRow = -1;

	m_Grid.SetColumnCount(m_nFieldCount+1);//设置列
	m_piRecordset->MoveLast();
	m_Grid.SetRowCount(1);//设置行
	m_piRecordset->MoveFirst();

	for(lFld = 0; lFld < m_nFieldCount; lFld++)
	{//显示字段名
		cName = (PCSTR)m_piRecordset->Fields->Item[lFld]->Name;//字段名
		m_Grid.SetItemText(0, lFld+1, cName);
	}
	while(!m_piRecordset->EndOfFile) 
	{//显示数据
		i = m_Grid.GetRowCount();
		cName.Format("记录%i:", i);
		m_Grid.InsertRow(cName);
		for (lFld = 0; lFld < m_nFieldCount; lFld++)
		{
			vValue = m_piRecordset->Fields->Item[lFld]->Value;//当前记录字段数据(可用MoveNext等命令移动)
			if(vValue.vt != 1)
			{//数据非空
				int type = vValue.vt;
				if(	VariantChangeType(&vValue1, &vValue, 0, VT_BSTR) == S_OK)//转换数据类型(为字符串)
				{
					cName = vValue1.bstrVal;
					m_Grid.SetItemText(i, lFld+1, cName);
				}
				else
				{
					m_Grid.SetItemText(i, lFld+1, _T(" "));
				}
			}
		}
		m_piRecordset->MoveNext();
	}
}

void CDemo5Dlg::OnAdd() 
{
	// TODO: Add your control notification handler code here
	if(m_nModified)
	{//按钮当前状态为“取消”
		m_Grid.SetEditable(false);
		m_nModified = 0;
		SetButtonCtrl();
		OnSelect();
	}
	else
	{//按钮当前状态为“增加”
		if(!m_bEditable)
		{
			AfxMessageBox("必须先查询船舶性能表,才能增加记录");
			return;
		}
		m_Grid.SetEditable(true);
		m_nSelectedRow = m_Grid.GetRowCount();
		CString name;
		name.Format("记录%d:", m_nSelectedRow);
		m_Grid.InsertRow(name);
		m_nModified = 1;
		SetButtonCtrl();
	}
}

void CDemo5Dlg::OnDelete() 
{
	// TODO: Add your control notification handler code here
	if(!m_bEditable)
	{
		AfxMessageBox("必须先查询船舶性能表,才能删除记录");
		return;
	}
	if(m_nSelectedRow>0)
	{
		m_piRecordset->MoveFirst();
		m_piRecordset->Move(m_nSelectedRow-1);
		m_piRecordset->Delete(adAffectCurrent);
		OnSelect();
	}
	else
	{
		AfxMessageBox("必须先选择一条记录,才能删除");
	}
}

void CDemo5Dlg::OnModify() 
{
	// TODO: Add your control notification handler code here
	if(!m_bEditable)
	{
		AfxMessageBox("必须先查询船舶性能表,才能修改记录");
		return;
	}
	if(m_nSelectedRow>0)
	{
		m_piRecordset->MoveFirst();
		m_piRecordset->Move(m_nSelectedRow-1);
		m_Grid.SetEditable(true);
		m_nModified = 2;
		SetButtonCtrl();
	}
	else
	{
		AfxMessageBox("必须先选择一条记录,才能修改");
	}
}

⌨️ 快捷键说明

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