Opening and Closing Datasets

From RAD Studio
Jump to: navigation, search

Go Up to Understanding Datasets Index


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 the Active property of the dataset to True, either at design time in the Object Inspector, or in code at run time.

 CustTable.Active := True;
 CustTable->Active = true;

Call the Open method for the dataset at run time.

 CustQuery.Open;
 CustQuery->Open();



When you open the dataset, the dataset first receives a Data.DB.TDataSet.BeforeOpen event, then it opens a cursor, populating itself with data, and finally, it receives an Data.DB.TDataSet.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 run time.

 
 CustQuery.Active := False;
 CustQuery->Active = false;

Call the Close method for the dataset at run time.

 CustTable.Close;
 CustTable->Close();


Just as the dataset receives BeforeOpen and AfterOpen events when you open it, it receives a Data.DB.TDataSet.BeforeClose and Data.DB.TDataSet.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);
 begin
   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 }
     end;
   end;
 end;
 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)
 DataSet->Post();
 else
 DataSet->Cancel();
 }
 }

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

See Also

Code Examples