RAD Studio
Opening and Closing Datasets

To read or write data in a dataset, an application must first open it. You can open a dataset in two ways:

Open Method 
Sample Code 
Set theActiveproperty of the dataset to True, either at design time in the Object Inspector, or in code at runtime.  
CustTable.Active := True; CustTable->Active = true;  
Call the Open method for the dataset at runtime.  
CustQuery.Open; CustQuery->Open();  

When you open the dataset, the dataset first receives a BeforeOpen event, then it opens a cursor, populating itself with data, and finally, it receives an AfterOpen event. 

The newly-opened dataset is in browse mode, which means your application can read the data and navigate through it. 

You can close a dataset in two ways:

Close Method 
Sample Code 
Set the Active property of the dataset to False, either at design time in the Object Inspector, or in code at runtime.  
CustQuery.Active := False; CustQuery->Active = false;  
Call the Close method for the dataset at runtime.  
CustTable.Close; CustTable->Close();  

Just as the dataset receives BeforeOpen and AfterOpen events when you open it, it receives a BeforeClose and AfterClose event when you close it. You can use these events, for example, to prompt the user to post pending changes or cancel them before closing the dataset. The following code illustrates such a handler:

procedure TForm1.CustTableVerifyBeforeClose(DataSet: TDataSet);
  if (CustTable.State in [dsEdit, dsInsert]) then begin
    case MessageDlg('Post changes before closing?', mtConfirmation, mbYesNoCancel, 0) of
      mrYes:    CustTable.Post;   { save the changes }
      mrNo:     CustTable.Cancel; { abandon the changes}
      mrCancel: Abort;            { abort closing the dataset }


void __fastcall TForm1::VerifyBeforeClose(TDataSet *DataSet)
if (DataSet->State == dsEdit || DataSet->State == dsInsert)
TMsgDlgButtons btns;
btns << mbYes << mbNo;
    if (MessageDlg("Post changes before closing?", mtConfirmation, btns, 0) == mrYes)

Note: You may need to close a dataset when you want to change certain of its properties, such as TableName on a TTable component. When you reopen the dataset, the new property value takes effect.

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!