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

📄 adodemodlg.cpp

📁 Visual_C++[1].NET_Bible1 Visual_C++宝典书中的全部源码
💻 CPP
字号:
// ADODemoDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ADODemo.h"
#include "ADODemoDlg.h"

#include "UpdateDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CAboutDlg dialog used for App About

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

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
public:
  afx_msg void OnBnClickedOk();
};

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

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

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
  ON_BN_CLICKED(IDOK, OnBnClickedOk)
END_MESSAGE_MAP()


// CADODemoDlg dialog



CADODemoDlg::CADODemoDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CADODemoDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CADODemoDlg::DoDataExchange(CDataExchange* pDX)
{
  CDialog::DoDataExchange(pDX);
  DDX_Control(pDX, IDC_LIST1, m_lstUsers);
}

BEGIN_MESSAGE_MAP(CADODemoDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
  ON_BN_CLICKED(IDOK, OnBnClickedOk)
  ON_BN_CLICKED(IDC_BUTTON1, OnBnClickedButton1)
END_MESSAGE_MAP()


// CADODemoDlg message handlers

BOOL CADODemoDlg::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

LONG lStyle = 
 m_lstUsers.SendMessage(LVM_GETEXTENDEDLISTVIEWSTYLE);

lStyle |= LVS_EX_FULLROWSELECT;

m_lstUsers.SendMessage(LVM_SETEXTENDEDLISTVIEWSTYLE, 
                      0, (LPARAM)lStyle);

try	
{
 // Initialie COM.
 CoInitialize(NULL);
 
 // Connecting to the database via a 
 // _ConnectionPtr interface
 m_pConnection.CreateInstance(__uuidof(Connection));
 m_pConnection->Open("DSN=VCNet Bible;",
                     _bstr_t(""),
                     _bstr_t(""),
                     adModeUnknown);

/* Uncomment this for a DSN-less connection
 m_pConnection->Open(_bstr_t("Provider=Microsoft.Jet."
                   "OLEDB.4.0;"
                   "Data Source = c:\\VCNETBIBLE.MDB"),
                   _bstr_t(""),
                   _bstr_t(""),
                   adModeUnknown);
*/

 if (NULL != m_pConnection)
 {                     
  DisplayUsers();
  SizeAllColumns();
 }
 else
 {
  AfxMessageBox("Could not acquire a Connection interface.");
 }
}
catch(_com_error &e)
{
 _bstr_t bstrError(e.ErrorMessage());
 CString strError = (char*)bstrError;		
 AfxMessageBox(strError);
}
catch (...)
{
 AfxMessageBox("Uknown Error!");
}
  	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CADODemoDlg::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 CADODemoDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<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 function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CADODemoDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CADODemoDlg::DisplayUsers()
{
 if (NULL != m_pConnection)
 {
  // Create columns for listview control.
  m_lstUsers.InsertColumn(0, "User ID");
  m_lstUsers.InsertColumn(1, "User Name");
  m_lstUsers.InsertColumn(2, "Status");

  try	
  {
   _CommandPtr pCommand;
   pCommand.CreateInstance (__uuidof (Command));
   pCommand->ActiveConnection = m_pConnection; 
   pCommand->CommandText = "Select * From UserMaster";
 	
   _RecordsetPtr pRecordset;
   pRecordset.CreateInstance (__uuidof (Recordset));
   pRecordset->CursorLocation = adUseClient;
   pRecordset->Open((IDispatch *) pCommand, 
                    vtMissing, 
                    adOpenStatic, 
                    adLockBatchOptimistic, 
                    adCmdUnknown);
		
   // Get the Fields collection from the recordset
   FieldsPtr pFields = pRecordset->Fields;

   // From the Fields collection get the desired Field
   FieldPtr pUserId = pFields->GetItem("sUserId");
   ASSERT(NULL != pUserId);
   
   FieldPtr pUserName = pFields->GetItem("sUserName");
   ASSERT(NULL != pUserName);
   
   FieldPtr pStatus = pFields->GetItem("iStatus");
   ASSERT(NULL != pStatus);

   // From the Field, get that field's properties collection
   PropertiesPtr pProperties = pUserName->Properties;

   // From the Properties collection, get the desired property
   PropertyPtr pProperty = pProperties->GetItem("Optimize");

   // Finally, set the desired property's value
   pProperty->Value = VARIANT_TRUE;
    	
   pRecordset->Sort = "sUserName";
   pRecordset->Filter = "sUserName LIKE 'K*'";
	
   _variant_t vUserId;
   _variant_t vUserName;
   _variant_t vStatus;
    
   int nUsers = 0;
   while (!pRecordset->adoEOF)
   {
    vUserId = pUserId->Value;
    vUserName = pUserName->Value;
    vStatus = pStatus->Value;
      
    if (vUserId.vt != VT_NULL)
    {
     CString strUserId = 	(char*)_bstr_t(vUserId);	
     int iIndex = m_lstUsers.InsertItem(nUsers++,
                                        strUserId,
                                        0);

     CString strUserName = (char*)_bstr_t(vUserName);
     m_lstUsers.SetItemText(iIndex, 1, strUserName);

     m_lstUsers.SetItemText(iIndex, 
                            2, 
                            ( 1 == vStatus.iVal 
                                ?  "Active" : "Inactive"));
    }

    pRecordset->MoveNext();
   }

   pRecordset->Filter = (long) adFilterNone;
  }
  catch(_com_error &e)
  {
   _bstr_t bstrError(e.ErrorMessage());
   CString strError = (char*)bstrError;		
   AfxMessageBox(strError);
  }
  catch (...)
  {
   AfxMessageBox("Uknown Error!");
  }
 }
 else
 {
  AfxMessageBox("No Connection interface was created in OnInitDialog");
 }
}

void CADODemoDlg::SizeAllColumns()
{
  CHeaderCtrl* pHeader = m_lstUsers.GetHeaderCtrl();
  ASSERT(pHeader);
  if (pHeader)
  {
    // Turn off redraw until the columns have all
    // been resized
    m_lstUsers.SetRedraw(FALSE);

    for (int iCurrCol = 0; 
        iCurrCol < pHeader->GetItemCount(); 
        iCurrCol++)
    {
      m_lstUsers.SetColumnWidth(iCurrCol, LVSCW_AUTOSIZE);

      int nCurrWidth = m_lstUsers.GetColumnWidth(iCurrCol);

      m_lstUsers.SetColumnWidth(iCurrCol,
                                LVSCW_AUTOSIZE_USEHEADER);

      int nColHdrWidth = m_lstUsers.GetColumnWidth(iCurrCol);

      m_lstUsers.SetColumnWidth(iCurrCol, 
                          max(nCurrWidth, nColHdrWidth));
    }

    // Now that sizing is finished, turn redraw back on and 
    // invalidate so that the control is repainted
    m_lstUsers.SetRedraw(TRUE);
    m_lstUsers.Invalidate();
  }
}

void CADODemoDlg::OnBnClickedOk()
{
 // Get selected item index from listview.
 POSITION pos = m_lstUsers.GetFirstSelectedItemPosition();
 if (NULL != pos)
 {
  // Code assumes one selection only.
  int nItem = m_lstUsers.GetNextSelectedItem(pos);
  ASSERT(-1 < nItem);
  if (-1 < nItem)
  {
   try	
   {
    HRESULT hr;

    _CommandPtr pCommand;
    hr = pCommand.CreateInstance (__uuidof (Command));
    if (SUCCEEDED(hr))
    {
     pCommand->ActiveConnection = m_pConnection;

     CString strUserId = 
      m_lstUsers.GetItemText(nItem, 0 /* first column */);

     CString strQuery;
     strQuery.Format("SELECT * FROM UserMaster WHERE "
                     "sUserId = \'%s\'", strUserId);
        
     pCommand->CommandText = (_bstr_t) strQuery;

     _RecordsetPtr pRecordset;
     hr = pRecordset.CreateInstance (__uuidof (Recordset));
     if (SUCCEEDED(hr))
     {
      pRecordset->CursorLocation = adUseClient;
      pRecordset->Open((IDispatch *) pCommand, 
                       vtMissing, 
                       adOpenStatic, 
                       adLockOptimistic, 
                       adCmdUnknown);

      // Instantiate the dialog and initialize 
      // it's DDX variables from the database.
      CUpdateDlg dlg;

      // Get the Fields collection from the recordset
      FieldsPtr pFields = pRecordset->Fields;

      // From the Fields collection get the desired Field
      FieldPtr pUserId = pFields->GetItem("sUserId");
      ASSERT(NULL != pUserId);
      
      FieldPtr pUserName = pFields->GetItem("sUserName");
      ASSERT(NULL != pUserName);

      dlg.m_strUserId = (char*)(_bstr_t)pUserId->Value;
      dlg.m_strUserName = (char*)(_bstr_t)pUserName->Value;

      if (IDOK == dlg.DoModal())
      {
       // Declare the two variants (column name and value)
       _variant_t vColumn, vValue;

       // Set the column name
       vColumn.SetString("sUserName");

       // Set the sUserName column's new value
       vValue.SetString(dlg.m_strUserName);

       // Update the column via the Recordset Update method
       pRecordset->Update(vColumn, vValue);

       // Update main dialog with new changes
       m_lstUsers.SetItemText(nItem, 1, dlg.m_strUserName);
      }

      pRecordset->Close();
     }
     else
     {
      AfxMessageBox("Failed to instantiate a "
                    "Recordset interface");
     }
    }
    else
    {
     AfxMessageBox("Failed to instantiate a "
                   "Command interface");
    }
   }
   catch(_com_error &e)
   {
    _bstr_t bstrError(e.ErrorMessage());
    CString strError = (char*)bstrError;		
    AfxMessageBox(strError);
   }
   catch(...)
   {
    AfxMessageBox("Uknown Error!");
   }
  }
  else
  {
   AfxMessageBox("Could not retrieve index of selected user");
  }
 }
 else
 {
  AfxMessageBox("Please select a user to edit.");
 }
}

void CAboutDlg::OnBnClickedOk()
{
  CWaitCursor wait;

  CString strUrl = "http://www.thecodechannel.com/redirect.asp?u=/&s=vcnb";
  if (32 >= (int)ShellExecute(NULL, "open", strUrl, NULL, NULL, SW_SHOWNORMAL))
  {
    AfxMessageBox("::ShellExecute failed to open this link!");
  }
}

void CADODemoDlg::OnBnClickedButton1()
{
  CAboutDlg().DoModal();
}

⌨️ 快捷键说明

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