Ad

Add Field To FDMemTable In Delphi

- 1 answer

I am coding something with DBGrid and there is not enough data witch i cen get with FDQuery. I would like custom data beside "FDQuery" data. I found component that should be able to do this and it is called FDMemTable. I can get data from FDQuery to FDMemTable, but I cant add a new field where I can put different data. So my question is how to propper connect the data with FDQuery and add extra column in FDMemTable.

procedure TWorkflowDM.Temp;
var
  Error: string;
  Temp: string;
begin
  try
    FDQuery1.Open;
    FDQuery1.FetchAll;
    FDMemTable1.Data:= FDQuery1.Data;
    FDMemTable1.FieldDefs.Add('Test', ftString, 20, False);        <-ERROR (Error 'FDMemTable1: Field ''Test'' not found')
    FDMemTable1.Open;
    FDMemTable1.First;
    while not FDMemTable1.Eof do
    begin
      Temp:= FDMemTable1.FieldByName('Test').AsString;
      FDMemTable1.Next;
    end;
  except
    on E: Exception do
      Error:= E.Message;
  end;
end;
Ad

Answer

We copy the field definitions from the source DataSet and append the additional fields. Then we call CreateDataset or optionally set Active to true. This creates all the necessary fields and opens the FDMemTable. Then we populate it by CopyDataset method. This code works:

procedure TWorkflowDM.Temp;
var
  Error: string;
  Temp: string;
begin
  try
    FDQuery1.Open;
    // FDQuery1.FetchAll;
    FDMemTable1.FieldDefs := FDQuery1.FieldDefs;
    FDMemTable1.FieldDefs.Add('Test', ftString, 20{, False}); // default parameter
    FDMemTable1.CreateDataSet;//or just Open that sets Active to true; 
    FDMemTable1.CopyDataSet(FDQuery1);
    FDMemTable1.First;
    while not FDMemTable1.Eof do
    begin
      Temp := FDMemTable1.FieldByName('Test').AsString;
      FDMemTable1.Next;
    end;
  except
    on E: Exception do
      Error := E.Message;
  end;
end;
Ad
source: stackoverflow.com
Ad