Deleting listview items in OnChange event causes crash lazarus / 31-LCL ---------------------------------------------------------------------- howardpc · 2014-01-20 23:38 The attached project has a button to add items to a listview (in vsReport style, though I don't think that is relevant). The listview's OnChange event monitors added items and if the total items count is over 4 it attempts to delete item zero. This leads to an access violation (on Win32). Other buttons delete items (either via item.Free, or via items.Delete() ) without problems. Can anyone see what is going wrong here, with the progammatic deletion in an OnChange event? ---------------------------------------------------------------------- taazz · 2014-01-21 00:02 Huge hint the tlistItem constructor's comments ee. Code: [Select]constructor TListItem.Create(AOwner : TListItems); begin   inherited Create;   FOwner := AOwner;   FFlags := [];   FStates := [];   FImageIndex := -1;   FSubItems := nil;     // We can't create ourself in the interface since we don't know out index here   // So interface creation is done in TListItems end;as far as I can see the onchange event is fired before the add function returns and I guess before the following code is executed Code: [Select]procedure TListItems.WSCreateCacheItem; begin   TWSCustomListViewClass(FOwner.WidgetSetClass).ItemInsert(FOwner, FCacheIndex, FCacheItem);   .... end;  making the FCacheIndex invalid and the insert of course fails, try to use a delayed deletion ee application.QueueAsyncCall() with a method that will delete the first item in the list. ---------------------------------------------------------------------- howardpc · 2014-01-21 09:21 Thanks for your insight. Using QueueAsyncCall() does indeed delay the delete and avoid the crash. However, it queues and repeats the Delete(0) call up to the last insert, effectively clearing the listview except for the latest item added. Is there a way to delay the Delete call, and have it called only once? ---------------------------------------------------------------------- taazz · 2014-01-21 11:51 ProcessAsyncCallQueue executes the given methods once and then removes them from the linked list. The only way that the method is executed multiple times is if you add it multiple times. ---------------------------------------------------------------------- howardpc · 2014-01-21 13:00 Ah, a little debugging shows that each ListView.Add fires the OnChange event four times. So a QueueAsyncCall() placed in OnChange gets called four times per item addition. Since my little example happened by chance to trigger deletion whenever there were more than four items, it looked like the call was repeating itself somehow, since I assumed incorrectly that OnChange is only fired once when adding a new list item. Thanks for your help.