tags:

views:

1060

answers:

4

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?

A: 

Would CloneCursor work for you?

Jim McKeeth
+2  A: 

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.

Jim McKeeth
It didn't work as I expected, some properties like "currency" weren't copied to the new dataset, I want to keep all the Field's settings in the cloned DataSet.
Fabio Gomes
+3  A: 

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

Richard Haven
+2  A: 

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.

Wouter van Nifterick