0

我有一个链接到 TTable 的 TDatasource,并且在 Datasource.OnDataChange 中执行了一些代码。

我的问题是,当我执行 TTable.First 或 TTable.Last 时,对每条记录执行 OnDataChange 中的代码,直到光标到达第一个或最后一个位置(我想与 TTable1.MoveBy 相同)。

如何确保 OnDataChange 中的代码在流程结束时只执行一次?

4

1 回答 1

0

I've had to deal with a similar situation recently. In my case, as an example, my code in the OnDataChange event was intended to adjust the column widths of an associated TDBGrid according to the latest data in the associated Dataset. I needed this adjustment to occur only when the data changed, but OnDataChange appeared to execute multiple times in succession.

So, how to make it execute the code only once?

I chose to use a Boolean flag to limit the execution of the code in the OnDataChange event to only when that flag is set to True. Something like this... (basic example code)

var
  bLoading: Boolean;

procedure TfrmMain.btnExecuteSQLClick(Sender: TObject);
begin
  qry.SQL := memo.Lines;
  bLoading := True; // set flag to true so code in OnDataChange will execute
  qry.Open;
end;    

procedure TfrmMain.DataSource1OnDataChange(Sender: TObject; Field: TField);
begin
  if bLoading then // checks if your flag is set to true
  begin
    // insert the code you want to run only once here
    ...
    bLoading := False; // then set flag to false to prevent repetitive execution
  end;
end;

I'm not sure if this helps you, and I know it doesn't answer the second part of your question "at the end of the process", but maybe just the idea of using Boolean flags will give you some inspiration to progress with your problem. It's a useful technique, and in the world of multithreaded programming they've even given it a special name. They call it a mutex!!! It's just a Boolean flag. Either the door is open, or it's closed. Once it's opened, make sure you shut the door behind you to prevent uninvited guests from crashing the party!

于 2013-10-22T23:21:24.957 回答