How To…Dynamic Variables in RAP

Question

“Is it possible to dynamically create multiple variables based on my data via RAP code?”

Solution

Use a TList object in RAP to keep track of each variable created in RAP. This way when you need to assign each value, you will have a reference to every variable you dynamically created. Use the OnCalc of an invisible variable as a way to assign each dynamic variable’s value. See the example below for more information.

Download: DynamicVarInRAP.zip

Sample RAP code:

//Create a TppVariable and add it to a global TList to keep track of it.
 
procedure AddNewVariable(aIndex: Integer);
var
  lVariable: TppVariable;
begin

  lVariable:= TppVariable.Create(nil);
  lVariable.Band := Summary;
  lVariable.DataType := dtDouble;
  lVariable.Top := 0.55 + (aIndex / 3);
  lVariable.Left := 3.8;
  lVariable.Width := 1;
  lVariable.Height := 0.5;
  lVariable.Font.Size := 14;
  lVariable.Font.Bold := True;
  lVariable.Value := 0;
      
  gVarList.AddObject(IntToStr(aIndex), lVariable);

end;

//Use the Report.BeforePrint event to determine how many variables 
//need to be created.

procedure ReportBeforePrint;
var
  liIndex: Integer;
  lVariable: TppVariable;
  liVendors: Integer;
begin

  liVendors := parts2['NumVendors'];
  gVarList := TStringList.Create;
  gLabelList := TList.Create;
  
  for liIndex := 0 to liVendors - 1 do
    begin
      AddNewVariable(liIndex);
      AddNewLabel(liIndex);
    end;
end;

//Use the OnCalc event of an invisible variable in the detail band
//to assign each dynamic variable's value.

procedure Variable1OnCalc(var value: Variant);
var
  lVariable: TppVariable;
  lLabel: TppLabel;
  lsVendorNo: String;
  liVendorIndex: Integer;
begin

   lsVendorNo := FloatToStr(parts['VendorNo']);
   liVendorIndex := gVarList.IndexOf(lsVendorNo);
   
   if liVendorIndex = -1 then
     begin
       lLabel := TppLabel(gLabelList[gVarTracker]);
       lLabel.Caption := lsVendorNo;    
     
       gVarList[gVarTracker] := lsVendorNo;
       
       lVariable := TppVariable(gVarList.Objects[gVarTracker]);
       lVariable.Value := parts['OnHand'];
       
       gVarTracker := gVarTracker + 1;
     end
   else
     begin
       lVariable := TppVariable(gVarList.Objects[liVendorIndex]);
       lVariable.Value := lVariable.Value + parts['OnHand'];
     end;
       

end;