Updating the Data Source with the Added Record

Add mode is completed when the user moves off the record. Enroll implements this by overriding the CRecordView::OnMove member function.

Suggested Reading

To implement Add functionality in the OnMove function override

  1. From the View menu, click ClassWizard.

  2. In the Class name box, click CSectionForm.

  3. In the Object IDs list, select CSectionForm.

  4. In the Messages box, select OnMove.

  5. Click Add function.

  6. Click Edit code to jump to the starter OnMove function, and replace the highlighted //TODO comment with the following code:
    if (m_bAddMode) 
    {
    if (!UpdateData())
    return FALSE;
    TRY
    {
    m_pSet->Update();
    }
    CATCH(CDBException, e)
    {
    AfxMessageBox(e->m_strError);
    return FALSE;
    }
    END_CATCH
    
    m_pSet->Requery();
    UpdateData(FALSE);
    m_ctlSection.SetReadOnly(TRUE);
    m_bAddMode = FALSE;
    return TRUE;
    }
    else
    {
    return CRecordView::OnMove(nIDMoveCommand);
    }
    

Catch any exceptions thrown by the recordset’s Update function so that errors are reported to the user. The CDBException data member m_strError is a fairly user-friendly error message, prepared by the underlying ODBC driver.

In its default CRecordView implementation, OnMove moves to the next, previous, first, or last record. If the application has changed the recordset field data members for the current record before the move, the framework updates the data source before moving to another record.

Note   Some ODBC drivers do not reflect newly added records in the recordset; others do. For those drivers that don’t display newly added records, to make the added records visible you must requery the database.

Step 3 augments the default CRecordView user interface for updating the current record. If the user is in add mode and then moves off the new record, Enroll adds the newly prepared record to the data source before moving to another record. But you must decide whether it’s important for added records to be immediately visible. For the tutorial, the decision is to requery the recordset (evident in the code above) after each add operation so the newly added record is included in the recordset.

Normally, the move commands behave as you might expect: Move Next moves to the next record, and so on. But as a consequence of the decision to requery during the add operation, when the user clicks any move command when adding a record, Enroll always effectively moves to the first record. That’s because requerying the recordset automatically sets the recordset to the first record.