我希望我的应用程序记住数据库表中的哪个选定行是 在应用程序关闭之前使用(选择),然后在下次加载(选择) 应用程序启动。该表只有4条记录,并且是只读的,所以如果有人,我不必担心 试图改变任何事情。现在我用 :

procedure TForm3.ClientDataSet1AfterOpen(DataSet: TDataSet);
begin
  Clientdataset1.DisableControls;
  try
    cxGrid1DBTableView1.DataController.KeyFieldNames := 'ID';
    cxGrid1DBTableView1.DataController.LocateByKey('4');
  finally
    Clientdataset1.EnableControls;
  end;
end;

但这是硬编码的。我希望它灵活。如何将这些设置保存到位于应用程序中的ini文件中。exe文件夹 并在应用程序启动时加载它们?所以,例如,如果key是'3' (当应用程序。退出)我下次加载它。

有帮助吗?

解决方案

使用 TDataSet.OnAfterOpenTDataSet.OnBeforeClose 加载和保存所需值的事件

procedure TForm3.ClientDataSet1AfterOpen(DataSet: TDataSet);
var
  LIni : TIniFile;
begin
  DataSet.DisableControls;
  try
    LIni := TIniFile.Create( '<YourIniFileName.ini>' );
    try
      DataSet.Locate( 'ID', LIni.ReadString( 'MyDataSet', 'ID', '' ), [] );
    finally
      LIni.Free;
    end;
  finally
    DataSet.EnableControls;
  end;
end;

procedure TForm3.ClientDataSet1BeforeClose(DataSet: TDataSet);
var
  LIni : TIniFile;
begin
  LIni := TIniFile.Create( '<YourIniFileName.ini>' );
  try
    LIni.WriteString( 'MyDataSet', 'ID', DataSet.FieldByName( 'ID' ).AsString ) );
  finally
    LIni.Free;
  end;
end;

这是一个非常 简单直截了当 样,你不应该在实际应用中实现这一点。

在实际应用程序中,您将委托给一个单例,该单例负责读取和写入此类应用程序值

// Very simple KeyValue-Store
IKeyValueStore = interface
  function GetValue( const Key : string; const Default : string ) : string;
  procedure SetValue( const Key : string; const Value : string );
end;

// Global Application Value Store as Singleton   
function AppGlobalStore : IKeyValueStore;

给你一个非常聪明的解决方案

procedure TForm3.ClientDataSet1AfterOpen(DataSet: TDataSet);
begin
  DataSet.DisableControls;
  try
    DataSet.Locate( 'ID', AppGlobalStore.GetValue( 'MyDataSet\ID', '' ), [] );
  finally
    DataSet.EnableControls;
  end;
end;

procedure TForm3.ClientDataSet1BeforeClose(DataSet: TDataSet);
begin
  AppGlobalStore.SetValue( 'MyDataSet\ID', DataSet.FieldByName( 'ID' ).AsString ), [] );
end;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top