Search code examples
delphidevexpressdelphi-xe4tcxgrid

Load table view on application start


I would like my application to remember which selected row in the database table was used (selected) before the application got closed and then load it (have it selected) the next time the application starts.The table has only 4 records and is read only so I dont have to worry if someone tries to change anything. Right now I use :

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

But this is hardcoded. I want it flexible. How can I save these settings to an ini file located in the application.exe folder and load them when the application starts ? So ,for example,if key was '3' (when the app. exited) I load it the next time.


Solution

  • Use the TDataSet.OnAfterOpen and TDataSet.OnBeforeClose events to load and save the desired values

    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;
    

    This is a very simple and straight forward sample and you should not implement this in real applications.

    In real applications you will delegate this to a singleton that takes care of reading and writing such application values

    // 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;
    

    and gives you a very smart solution

    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;