I am trying to implement MoveItemUp and MoveItemDown methods that move a selected row up or down one index within a TCollection.
The following code added to my subclass of TCollection does not work:
procedure TMyCollection.MoveRowDown(index: Integer);
var
item:TCollectionItem;
begin
if index>=Count-1 then exit;
item := Self.Items[index];
Self.Delete(index); // whoops this destroys the item above.
Self.Insert(index+1);
Self.SetItem(index+1,item); // this actually does an assign from a destroyed object.
end;
I am fairly sure this must be possible at runtime, as its done in designtime by the Delphi IDE itself which provides a way to reorder Collection items in a list. I am hoping to do this by simply reordering existing objects, without creating, destroying, or Assigning any objects. Is this possible from a subclass of Classes.pas TCollection? (If not, I may have to make my own TCollection from a source clone)
According to the VCL source, you don't need to manually do that. Simply set the Index property like @Sertac suggested and it should work just fine. If you have the source, check out the code of TCollectionItem.SetIndex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With