Visual Basic Concepts

Saving and Retrieving Embedded Data

Data associated with an embedded object is not persistent; that is, when a form containing an OLE container control is closed, any changes to the data associated with that control are lost. To save updated data from an object to a file, you use the OLE container control's SaveToFile method. Once the data has been saved to a file, you can open the file and restore the object.

If the object is linked (OLEType = 0-Linked), then only the link information and an image of the data is saved to the specified file. The object's data is maintained by the application that created the object. If a user wants to save changes to a linked file, the user must choose the Save command from the ActiveX component's File menu because the SaveToFile method applies only to embedded objects.

If the object is embedded (OLEType = 1-Embedded), the object's data is maintained by the OLE container control and can be saved by your Visual Basic application.

Objects in the OLE container control can be saved only to open, binary files.

To save the data from an object to a file

  1. Open a file in binary mode.

  2. Use the SaveToFile method.

The cmdSaveObject_Click event procedure illustrates these steps:

Private Sub cmdSaveObject_Click ()
   Dim FileNum as Integer
   ' Get file number.
   FileNum = FreeFile
   ' Open file to be saved.
   Open "TEST.OLE" For Binary As #FileNum
   ' Save the file.
   oleObj1.SaveToFile FileNum
   ' Close the file.
   Close #FileNum
End Sub

Once an object has been saved to a file, it can be opened and displayed in an OLE container control.

Note   When you use the SaveToFile or ReadFromFile methods, the file position is located immediately following the object. Therefore, if you save multiple objects to a file, you should read them in the same order you write them.

To read data from a file into an OLE container control

  1. Open the file in binary mode.

  2. Use the ReadFromFile method on the object.

The cmdOpenObject_Click event procedure illustrates these steps:

Private Sub cmdOpenObject_Click ()
   Dim FileNum as Integer
   ' Get file number.
   FileNum = FreeFile
   ' Open the file.
   Open "TEST.OLE" For Binary As #FileNum
   ' Read the file.
   oleObj1.ReadFromFile FileNum
   ' Close the binary file.
   Close #FileNum
End Sub

The Updated event is invoked each time the contents of an object is changed. This event is useful for determining if an object's data has been changed because it was last saved. To do this, set a global variable in the Updated event indicating the object needs to be saved. When you save the object, reset the variable.