See Chapter 14 of 'Teach Yourself Visual C++ 6 in 21 Days' for the background to this article.
In Chapter 13 of 'Teach Yourself Visual C++ 6 in 21 Days', you learn how there is a nice, complete, and very rounded way of making sure that data from a straightforward class is practically always saved. This is the 'Serialization' framework. However, when I built the example in Chapter 14, an application which uses a class inherited from the
RecordView class, I found that I couldn't find a way to use the serialization framework. This meant that it was possible to edit a field, close the application, and data from that field would be lost. I posted my concerns to microsoft.public.vc.mfc, and got some useful replies - and with a bit of Googling, came up with the solution described here. This is what I did:
- Created a function
CView::OnChange() to handle the control's
- At this point, I realized that I needed to call the
UpDateData function in the view class from the
CDoc::SaveModified() function. I couldn't work out how to access the view class, so I did some searches on Google, and found the following information from http://www.codeproject.com/docview/cviewaccess.asp posted by kin...
MFC (Access to CView from Anywhere)
This is the cheats way of getting access to
CView from anywhere in your application.
- In you
CWinApp, create two functions: a
StoreMyView (CView* pView), and a
- Declare a pointer of type
CView in the
- In the
CView constructor, get the application using the following lines:
CWinApp* pApp = (CWinApp*) AfxGetApp ();
CWinApp GetMyView(), return your declared pointer.
CWinApp StoreMyView, point your data member to the parameter value. Say, the data member is
m_pView and the parameter is
m_pView = pView;.
- Now, you can access your view using the application object, i.e.:
CWinApp * pApp = (CWinApp*) AfxGetApp ();
CView * pView = pApp. GetMyView ();
- Don't forget to include View.h and Doc.h in CWinApp.h, and view.h is included in .cpp files automatically when you create your data member in VC++.
That's all folks. Any comments, mail to: firstname.lastname@example.org.
I used this method and it seems to do exactly what I wanted. I would love to know why the author says it is a cheat though.
- Using the above method, my
CDoc::SaveModified() turned out as follows...
if (AfxMessageBox("There is unsaved data. Do you want to save it?",
if (m_dbOdbcSet.CanUpdate() && !m_dbOdbcSet.IsDeleted())
CApp * pApp = (CApp*) AfxGetApp ();
CView * pView = pApp-> GetMyView ();