I would like to program the following situation:
I have 2 different ListViews in a form. I would like to attach specific items from ListView2 into a ListView1 item. After the “Parent” Item gets deleted, it should also delete all the attached items from ListView2.
I tried this so far:
type
TITEMS = record
A_Items : array of TListItem;
end;
A Button that adds an item to ListView1 (ParentItems)
var
item : TListItem;
begin
item := ListView1.Items.Add;
item.Caption := 'ParentTestItem';
item.SubItems.Add('TestSubItem');
A button that adds an item to ListView2 (ChildItems)
var
item : TlistItem;
items : TITEMS;
begin
if ListView1.Selected = NIL then exit; // Make sure an item is selected.
item := ListView2.Items.Add;
item.Caption := 'ChildTestItem';
item.SubItems.Add('TestSubItem');
SetLength (items.item, Length(items.item) + 1); // wrong?
items.item[Length(items.item)-1] := item;
ListView1.Selected.SubItems.Objects[0] := @items;
A button that removes a ParentItem (and it should delete ChildItems as well…)
var
items : TItems;
i : Integer;
item : TlistItem;
begin
if ListView1.Selected = NIL then exit; // Make sure an item is selected.
items := TItems(ListView1.Selected.SubItems.Objects[0]); // Cast
for i := 0 to Length (items.item) - 1 do begin
item := items.item[i];
item.Delete;
end;
ListView1.Selected.Free;
Any Idea how I could realize this?
You need to allocate the list of items dynamically on the heap, not locally on the stack, so it stays valid in memory while you are using it.
I would suggest using a
TListinstead of an array, it is easier to allocate dynmically. I would also suggest using theTListItem.Dataproperty instead of theTListItem.SubItems.Objects[]property (unless you are already using theDataproperty for something else).