user2175495
user2175495

Reputation:

Copy record from one Table to another not working

I am using the BDE and flat Tables. I have two identical Tables, tblOne and tblTwo I am trying to copy the data from one table to the other. Not the entire DB, just one specific Record using this:

function Tdm.CopyRecord(var tblFrom,tblTo : TTable) : Boolean;
var
  i : Integer;
begin
  Result:=False;
  try
    tblTo.Insert;
    for i:=1 to tblFrom.FieldCount-1 do
    begin
      if tblFrom.Fields[i].FieldName = tblTo.Fields[i].FieldName then
        tblTo.Fields[i].Value:=tblFrom.Fields[i].Value;
    end;
    tblTo.Post;
    Result:=True;
  finally
  end;
end;

if CopyRecord(tblOne,tblTwo) then...

Stepping through this all of the Values are "Null" for the From Table.

After the Post I get a blank record added to the tblTo. Not surprising with all the Values a Null. :)

Where am I going wrong in copying the data? It is not making it to the Copy function.

I have been at this for several hours and cannot make it work. Probably something simple I am over-looking. I added the "var" parameter to see if that made any difference but it did not.

Oh, by the by, I am starting the loop from "1" not "0" as the first field in both files is an AutoInc.

Upvotes: 1

Views: 6366

Answers (1)

kobik
kobik

Reputation: 21252

Here is how I would do it:

function CopyRecord(tblFrom, tblTo: TTable; const StartIndex: Integer=0): Boolean;
var
  i: Integer;
  FieldFrom, FieldTo: TField;
begin
  Result := False;
  for i := StartIndex to tblFrom.FieldCount - 1 do
  begin
    FieldFrom := tblFrom.Fields[i];
    FieldTo := tblTo.FindField(FieldFrom.FieldName);
    if Assigned(FieldTo) then
    begin
      FieldTo.Value := FieldFrom.Value;
      Result := True;
    end;
  end;
end;

I would not use tblTo.Insert/tblTo.Post inside the CopyRecord method. but rather use it outside e.g:

tblTwo.Append;
if CopyRecord(tblOne, tblTwo, 1) then
  tblTwo.Post
else
  tblTwo.Cancel;

This could be re-used also in Edit mode.

Upvotes: 5

Related Questions