21.4.4 创建记录集视图(1)
现在可以创建与新对话框连接的记录集视图类,因此给该项目添加.h文件和.cpp文件,以容纳即将定义的新类CCustomerView和CProductView的代码,使用Solution Explorer实现该操作。CCustomerView类封装了CCustomerSet记录集的视图,并使用了IDD_CUSTOMER_FORM对话框资源。最初的类定义因此如下所示:
- // CustomerView.h : header file
-
- #pragma once
-
- class CCustomerSet;
-
- class CCustomerView : public CRecordView
- {
- public:
- CCustomerView();
- virtual ~CCustomerView();
-
- public:
- enum { IDD = IDD_CUSTOMER_FORM };// Form Data
- CCustomerSet* m_pSet;
-
- // Operations
- public:
- CCustomerSet* GetRecordset();
-
- #ifdef _DEBUG
- virtual void AssertValid() const;
- virtual void Dump(CDumpContext& dc) const;
- #endif
-
- };
在CustomerView.cpp文件中,可以在构造函数中初始化将存储记录集对象指针的m_pSet成员:
- #include "stdafx.h"
- #include "DBSimpleUpdate.h" // Main header file for the application
- #include "CustomerView.h"
-
- // Constructor
- CCustomerView::CCustomerView()
- : CRecordView(CCustomerView::IDD),
- m_pSet(NULL)
- {
- }
另外,此构造函数通过将对话框窗体的ID传递给基类的构造函数,使IDD_CUSTOMER_FORM成为该视图的对话框。在嵌入CustomerView.h头文件的#include指令之前需要有嵌入DBSimpleUpdate.h的#include指令,不然编译过程中将不能识别IDD_CUSTOMER_FORM符号。DBSimpleUpdate.h文件中有一条嵌入Resource.h的#include指令,而Resource.h文件中定义了已创建资源的ID。
现在,在CustomerView.cpp文件中添加那些将在调试模式中生成的函数的定义:
- // CCustomerView diagnostics
-
- #ifdef _DEBUG
- void CCustomerView::AssertValid() const
- {
- CRecordView::AssertValid();
- }
-
- void CCustomerView::Dump(CDumpContext& dc) const
- {
- CRecordView::Dump(dc);
- }
- #endif //_DEBUG
可能不会需要这些函数,但定义它们没什么坏处;万一发生故障时,它们将派上用场。
现在,可以重写从基类继承的DoDataExchange()、OnGetRecordset()和OnInitialUpdate()函数。该示例将展示为了使这些函数以需要的方式处理记录集,应该如何对它们进行定制。在Class View中右击CCustomerView类名,并从弹出菜单中选择Properties。单击重写工具栏按钮(如果不记得是哪个按钮,可以等待屏幕上显示按钮的工具提示),并在左列中选择要重写的函数名,然后在右边单元格中选择<Add>选项以添加函数。
我们即刻就能完成OnGetRecordset()重写函数的实现:
- CRecordset* CCustomerView::OnGetRecordset()
- {
- if(m_pSet == NULL) // If we don't have the recordset address
- {
- m_pSet = new CCustomerSet(NULL); // create a new one
- m_pSet->Open(); // and open it
- }
- return m_pSet; // Return the recordset address
- }
如果m_pSet是NULL,就创建一个记录集,并将其打开,然后返回它的地址。如果m_pSet不是NULL,则表明已经有被创建的记录集,因此返回m_pSet包含的地址。必须给.cpp文件添加一条嵌入CCustomerSet.h的#include指令,因为这里要引用CCustomerSet类名。
现在,可以实现使用OnGetRecordset()函数的GetRecordset()函数:
- CCustomerSet* CCustomerView::GetRecordset()
- {
- return static_cast<CCustomerSet*>(OnGetRecordset());
- }