How can I catch the event when an item is added to TListView?
I thought the OnInsert
event would do the job, according to the documentation. It even passes the actual TListItem
object to the handler:
OnInsert Occurs immediately after a new item is inserted into the list view.
Write an OnInsert event handler to respond when an item has just been added to the list. The Item parameter is the TListItem object that was added to the Items property
Here is my code:
procedure TForm1.Button1Click(Sender: TObject);
begin
with ListView1.Items.Add do
begin
Caption := 'foo';
SubItems.Add('bar');
end;
end;
procedure TForm1.TListView1Insert(Sender: TObject; Item: TListItem);
begin
//Item is empty
ShowMessage(Item.Caption);
end;
But surprisingly, the Item.Caption
is always empty. Seems nonsense to me.
EDIT:
Switching to Items.AddItem()
, as suggested, leads to another weird issue.
The OnInsert
event handler now works as expected, however TListView
does not display the TListItem.Caption
.
procedure TForm1.Button1Click(Sender: TObject);
begin
with ListView1.Items.Add do
begin
Caption := 'foo1';
SubItems.Add('bar1');
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
item: TListItem;
begin
item := TListItem.Create(ListView1.Items);
item.Caption := 'foo2';
item.Subitems.Add('bar2');
ListView1.Items.AddItem(item);
end;
procedure TForm1.ListView1Insert(Sender: TObject; Item: TListItem);
begin
//this now works as expected
ShowMessage(Item.Caption);
end;
Why is this?