Edit - worked example
key : purple - original code / blue - new code
Step 1 :
Continue with the program names.
Step 2 :
A dialog box should be designed for the OnEditCurrentName() interface. This can be called CEditNamesDlg and should be of a pop-up style and be derived from a CDialog base class. This should be done using the same method outlined previously in the dialog task. The following code should be added to the handler function :
void
CNamesDoc::OnEditCurrentName()
{
if( !m_NameList.IsEmpty() )
{CEditNamesDlg dlg;
CName * pNameTemp = m_NameList.GetAt(m_nCurrentPosition);
dlg.m_strFirstName = pNameTemp->GetFirstName();
dlg.m_strSecondName = pNameTemp->GetSecondName();
if(dlg.DoModal() == IDOK)
{pNameTemp->SetFirstName(dlg.m_strFirstName);
pNameTemp->SetSecondName(dlg.m_strSecondName);
UpdateAllViews(NULL);}
}
else
{AfxMessageBox("There are no items to edit.");
}
}
Step 3 :
The following code should be added to the OnRemoveCurrentName() function :
void
CNamesDoc::OnRemoveCurrentName()
{
if( !m_NameList.IsEmpty() )
{//Store current item to be deleted
CName * pCurrentName = GetCurrentName();
//First sort out new current item
POSITION nTemp = m_nCurrentPosition;
m_NameList.GetNext(m_nCurrentPosition);
if(m_nCurrentPosition==NULL)
{m_nCurrentPosition = nTemp;
m_NameList.GetPrev(m_nCurrentPosition);}
//Now delete current item
UpdateAllViews(NULL,DELETE,pCurrentName);
m_NameList.RemoveAt(nTemp);
delete pCurrentName;}
else
{AfxMessageBox("There are no items to delete.");
}
}
Step 4:
The following code should be added to the OnRemoveAllNames() function :
void
CNamesDoc::OnRemoveAllNames()
{
if( !m_NameList.IsEmpty() )
{
// firstly delete all the pointers to avoid memory leaks
POSITION pos = m_NameList.GetHeadPosition();
while( pos != NULL )
{
delete m_NameList.GetNext( pos );
}// now delete all the m_NameList
m_NameList.RemoveAll();
m_nCurrentPosition = NULL;
UpdateAllViews(NULL);
}
else
{AfxMessageBox("There are no items to delete.");
}
}
Click here for the basic exercise
Click here for the source code
Click here to return to menu