Step 3 implements a user interface for Add that closely parallels CRecordView’s default user interface for modifying an existing record. The user starts a new record with the Add command on the Record menu.
In response to the Add command, the record view calls its OnRecordAdd
member function and enters an “add mode” by setting an m_bAddMode
data member to TRUE. The add mode is completed when the user moves off the record. The Step 3 implementation overrides the record view’s OnMove member function to implement completion of the add mode. The following procedures implement the add mode, and create a CEdit member variable used to turn on and off the read-only style of the Section edit control.
To implement the Add mode
m_bAddMode
data member:protected:
BOOL m_bAddMode;
m_bAddMode
in the CSectionForm
constructor in file SectionForm.cpp. (You can jump directly to the constructor from ClassView.) Add the following line after the //}}AFX_DATA_INIT
line:m_bAddMode = FALSE;
In Steps 1 and 2 of the tutorial, the Section control was read-only because it was necessary to prevent the user from changing this primary key value of the Section record. In Step 3, you need to turn off the read-only style of the Section control when the user is in add mode. The control is still read-only if the user is in browse/update mode rather than add mode.
To change the read-only style, you must call the CEdit member function SetReadOnly with the appropriate parameter. This requires a member variable of type CEdit in CSectionForm
. At this point, the class has a CString data member representing the Section control, but you need a CEdit member variable as well.
To define the CEdit member variable
IDC_SECTION
, which is already associated with a CString member.m_ctlSection
.Notice that the Variable Type box changes appropriately to CEdit.
Notice that a second member variable is now associated with the IDC_SECTION
control ID. You access the control’s value through m_pSet->m_SectionNo
. You access the control itself, to call its member functions, through m_ctlSection
.
The Add command initiates add mode and calls the recordset’s AddNew function to prepare a new record, but doesn’t add the record to the data source. The record isn’t actually added to the data source until a subsequent call to OnMove
calls the recordset’s Update function.
To implement the OnRecordAdd command handler function
OnRecordAdd
starter handler that ClassWizard created in SectionForm.cpp.// If already in add mode, complete the previous new record
if (m_bAddMode)
OnMove(ID_RECORD_FIRST);
CString strCurrentCourse = m_pSet->m_CourseID;
m_pSet->AddNew();
m_pSet->SetFieldNull(&(m_pSet->m_CourseID), FALSE);
m_pSet->m_CourseID = strCurrentCourse;
m_bAddMode = TRUE;
m_ctlSection.SetReadOnly(FALSE);
UpdateData(FALSE);
The most important line of this code is the call to CRecordset::AddNew, which prepares a new record. The rest of the code does the following: