How to assign dataset dynamically in FastReport?

sinu picture sinu · Oct 31, 2010 · Viewed 25.4k times · Source

I have created a report using FastReport Designer and calling it using Delphi 6. But DataSet for the MasterData and the fields is not assinged at design time. I want to set these properties at runtime based on the selected DataSet. How can I do that? How can I access the DataSet of the MasterData in Delphi before calling the preview/print/design? Added following code in frxReport1BeforePrint.

  t := frxReport1.FindObject('MasterData1') as TfrxMasterData;
  //if Assigned(t) then
    //t.DataSet := frxIBODataset1;

  m := frxReport1.FindObject('mTenderType') as TfrxMemoView;
  if Assigned(m) then
  begin
    m.DataSet := frxIBODataset1;
    m.DataField := 'ACCOUNTNAME';
    m.Text := '[frxIBODataset1."ACCOUNTNAME"]';
  end;

But I need to set these properties before calling the print/design/preview. Any help is appreciated.

Answer

vcldeveloper picture vcldeveloper · Nov 1, 2010

You should first specify whether you are trying to use a dataset defined in your application, or a dataset defined directly in your report (Data tab in FastReport designer)?

If you are trying to use a dataset which is defined inside your application (e.g. an AdoDataset instance defined in one of your data-modules), for such a purpose, you don't have to bind the MasterBand to your dataset. dynamically. Inside the report, your MasterBand is bound to a TfrxDbDataset instance in design time. At runtime, your frxDbDataset instance can be connected to any dataset in your project.

Here is how it would be:

1- You drop a frxReport component and a frxDbDataset component on your form or data-module. 2- In the report designer, you go to Datasets section, and add the available frxDbDataset to the report's dataset list. 3- You add a master-data band, and assign the frxDbDataset to its Dataset property. 4- Now in your code, before showing or preparing the report, you can write something like this:

  if MyOption = 1 then
    frxDbDataset1.Dataset := AdoDataset1
  else
    frxDbDataset1.Dataset := AdoDataset2;

Whatever you assign to frxDbDataset will be printed by the master-band in your report.

If you are defining the dataset directly inside the report, using FastReport designer; then everything is inside your report. Just open fastreport designer and do this:

1- Go to Data tab and define your datasets (e.g. AdoQuery1). 2- Select Report object from Report Tree pane. 3- In the object inspector go to Events tab. 4- Choose a proper event; OnStartReport is a good event for your job. Double-click on it to open the code editor. 5- Now you can assign the dataset defined in data-tab to the master-data band using PascalScript code. Something like this:

procedure frxReport1OnStartReport(Sender: TfrxComponent);
begin
  MasterData1.Dataset := <ADOQuery1."ADOQuery1">;      
end;