The MFC Professional Stingray Software

NEWBIE TIP #6
Getting from a view to the document, and vice-versa


You have a view, and you need to find the corresponding document. Or, you have a document, and you need to find the corresponding view.

Remember that there is a one-to-many mapping from CDocument to CView. That means that while a document can have many views, a view has but one (exactly one) document. Think of the Scribble app (and shame on you if you never tried to follow along with it ). Remember how you can use a splitter window and view different portions of the same document? Two views, one document.

Since every view must have one and only one document, it stands to reason that it has a data member dedicated for just that purpose. It's m_pDocument. When AppWizard creates a derived document class for you, it creates an inline function called GetDocument, which returns a type-safe pointer to your document object.

If you have more than one view, you update them using the CDocument::UpdateAllViews function. If you really want to iterate through all your views manually, use the CDocument::GetFirstViewPosition and the CDocument::GetNextView functions as illustrated in the code below.

See also Chapter 15 of David Kruglinski's excellent book, Inside Visual C++ Version 4.


// To get the document for a given view.
pView->GetDocument();  // pView is a CView*

// To get the first view in the list of views.
POSITION pos = GetFirstViewPosition();
CView* pFirstView = GetNextView(pos);

// To loop through the list of views.
POSITION pos = GetFirstViewPosition();
while (pos)
{
    CView* pView = GetNextView(pos);
    // Use the view.
}


Source code is provided for instructional purposes, and is released to the public domain. No claim of ownership is made. Use it at your own risk. No warranties are expressed or implied. The resulting program may not be fully functional. No animals were used to test this code.

| Past Tips | Future Tips | Home |

Comments on this Tip? Send us mail.
(Be sure to put the Tip # in the subject.)

Got an idea for a Tip you'd like us to write? Let us know.

Solved a problem lately that would make a good Tip? PLEASE tell us about it!!!
We'll give you prominent credit, and we'll even buy you a beer next time you're in town.