在delphi中使用数据模块分离数据集实例数据、实例、模块、delphi

2023-09-06 04:47:42 作者:此用户已下落不明

我正在使用 Delphi6 并且有一个带有 ADO DataSet 的数据模块,它被两种形式使用,formA 和 FormB.每个表单在 OnCreate 中都有一个 Dataset.Open() 和在 OnClose 中的 Dataset.Close().如果两个表单同时打开并且 formB 关闭,则数据集在 formA 中关闭.我该如何防止这种情况,基本上我需要为每个表单提供单独的数据集实例,但同时使用数据模块.

I am using Delphi6 and have a data module with an ADO DataSet which is used by two forms, formA and FormB. Each form has a Dataset.Open() in OnCreate and Dataset.Close() in OnClose. If both forms are open simultaneously and formB is closed the dataset is closed in formA. How can I prevent this, essentially I need separate instances of the dataset for each form but at the same time use the datamodule.

推荐答案

实现你想要的最简单的方法是为每个表单创建一个数据模块的实例,并将其传递给表单,以便在何时释放它表格已关闭:

The simplest way to achieve what you want is to create an instance of the data module for each form, and pass it to the form so it can be freed when the form is closed:

var
  Data: TDataModule;
begin
  Data := T<YourDataModule>.Create(Self);
  try
    Form := T<YourForm>.Create(Self);
    Form.DataModule := Data;
    Data.Name := '';
  except
    Data.Free;
    raise;
  end;

  Form.Show;
end;

将 DataModule 的名称设置为空字符串是为了确保 VCL 用于将数据感知控件连接到其数据源/数据集的逻辑是使用新创建的实例而不是第一个实例完成的.

Setting the DataModule's Name to an empty string is done to ensure that the VCL's logic for hooking up data aware controls to their datasource/dataset is done using the newly created instance, instead of the first ever instance.

在表单的 OnClose 处理程序(或其析构函数)中,确保释放数据模块.

In the Form's OnClose handler (or its destructor) make sure to free the data module.