croceldon
croceldon

Reputation: 4595

Delphi: How to copy forms

I'm trying to copy, or 'exchange' two forms that are referenced by a TListBox.

Here's what I'm trying to do, but I get an error (shown below):

      cf1 := TCustomform(lstPackages.Items.Objects[origNdx]);
      cf2 := TCustomform(lstPackages.Items.Objects[origNdx - 1]);

      cfTmp.Assign(cf1); //error here: cannot assign TfPackage to a TfPackage
      cf1.Assign(cf2);
      cf2.Assign(cfTmp);

      lstPackages.Items.Exchange(origNdx, origNdx - 1);
      lstPackages.ItemIndex := origNdx - 1;

So, I'm trying to exchange the list items, and I need to do something similar with the forms, but I get the error that I can't assign the form type that I'm using. TfPackage is a descendant of TCustomForm.

How can I accomplish the same thing?

Upvotes: 2

Views: 2161

Answers (1)

Mason Wheeler
Mason Wheeler

Reputation: 84550

You don't have to do this. TStrings.Exchange exchanges the objects as well as the strings, so it's already taken care of for you. The same form objects will stay associated with the same strings.

EDIT: In response to the comment, if you need to exchange the position of the forms in another list, then that's not difficult. You've got the basic idea right when you said:

cfTmp.Assign(cf1);
cf1.Assign(cf2);
cf2.Assign(cfTmp);

But you're not trying to copy the objects, you're trying to swap references to them. Objects are not records. In Delphi, all object variables, including the ones in the form container, are references (hidden, implicit pointers) to the object. So what you need to do is:

cfTmp := list[cf1Position];
list[cf1Position] := list[cf2Position];
list[cf2Position] := cfTmp;

Upvotes: 1

Related Questions