Question

I have a function that returns a TADODataset object:

// inside DataModule:

function TDM.GetWorkstationsList: TADODataset;
var
  DS: TADODataSet;
begin
  DS := TADODataSet.Create(nil);
  DS.Connection := MyConnection;  // MyConnection is TADOConnection
  DS.CommandType := cmdText;
  DS.CommandText := 'SELECT * FROM Workstation';
  DS.Active := True;
  Result := DS;
end;

This is how I plan to use it:

// inside main form: 

tvWorkstation.DataController.DataSource.DataSet := DM.GetWorkstationsList; // tvWorkstation is TcxGridDBTableView

As far as I know, if I create an object manually in runtime, I must destroy it manually at some moment to avoid memory leaks. How and when should I destroy my created dataset?

Was it helpful?

Solution

You can simply make use of Delphi's ownership mechanism. You can pass in an owner (of type TComponent) in the constructor and then your data set will be destroyed whenever the owner is destroyed. In your case, just pass the form as the owner.

function TDM.CreateWorkstationsList(Owner: TComponent): TADODataSet;
begin
DS := TADODataSet.Create (Owner);
...
end;

DataSource.DataSet := DM.CreateWorkstationsList (Self);

You could also destroy the data set manually, for example in the form's OnDestroy event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top