Fabio Gomes
Fabio Gomes

Reputation: 6022

Is there some better way to copy all DataSet Fields and their properties to another DataSet?

I'm cloning a TClientDataSet and I want to copy all the fields to the clone (which is a new DataSet), I know I can loop through the Fields and copy the info, or make 2 instances of my class and just clone the cursor, but is there some better way? Something like create a new DataSet and assign the fields info?

EDIT:

The following class helper method works for me:

procedure TDataSetHelper.CopyFieldDefs(Source: TDataSet);
var
  Field, NewField: TField;
  FieldDef: TFieldDef;
begin
  for Field in Source.Fields do
  begin
    FieldDef := FieldDefs.AddFieldDef;
    FieldDef.DataType := Field.DataType;
    FieldDef.Size := Field.Size;
    FieldDef.Name := Field.FieldName;

    NewField := FieldDef.CreateField(Self);
    NewField.Visible := Field.Visible;
    NewField.DisplayLabel := Field.DisplayLabel;
    NewField.DisplayWidth := Field.DisplayWidth;
    NewField.EditMask := Field.EditMask;

   if IsPublishedProp(Field, 'currency')  then
     SetPropValue(NewField, 'currency', GetPropValue(Field, 'currency'));

  end;
end;

Anyone has a better way for doing this?

Upvotes: 8

Views: 17791

Answers (5)

OldManSam
OldManSam

Reputation: 39

NON-PROGRAMMABLE METHOD

  • first tclientdataset: open fields editor. add all fields if not already shown. select all fields. copy to clipboard.

  • second tclientdataset: open fields editor. paste clipboard in fields editor. done

you should now see identical fieldDefs for both tclientdatasets now.

Upvotes: 0

Wouter van Nifterick
Wouter van Nifterick

Reputation: 24116

If you're going to loop through the dataset to make a copy, remember to call DisableControls on it before, and EnableControl afterwards.

Without that, things can get really slow if you've got visual controls showing the data of the dataset on your form.

Upvotes: 2

Richard Haven
Richard Haven

Reputation: 1154

Are you looking for a more aesthetic way of doing it or a faster way of doing it?

If the former, create your own classes that hide the loop.

If the latter, don't even worry about it. A very wise coder once said to me: disk access costs; network access costs; maybe screen access costs; everything else is free.

Don't confuse the size of the source code with execution time. Looping a thousand times through memory and copying bits is undetectable compared to the initial handshake of a database connection.

Cheers

Upvotes: 5

Jim McKeeth
Jim McKeeth

Reputation: 38723

If you just want to copy the field definitions you can do the following:

ds2.FieldDefs.Assign(ds1.FieldDefs);
ds2.CreateDataSet;
ds2.Open;

Of course this assumes you created FieldDefs for ds1.

Upvotes: 11

Jim McKeeth
Jim McKeeth

Reputation: 38723

Would CloneCursor work for you?

Upvotes: 1

Related Questions