ListView.Items.Delete causes excepion
Original Reporter info from Mantis: Martin @martin_frb
-
Reporter name: Martin Friebe
Original Reporter info from Mantis: Martin @martin_frb
- Reporter name: Martin Friebe
Description:
See the code below. It throws an exception "index 1 out of bounds" on the 2nd delete.
The reason is FCacheIndex = 1 / lcl\include\listitems.inc line 280
procedure TListItems.ItemDestroying(const AItem: TListItem);
var
idx: Integer;
begin
// Don't use IndexOf, it updates the cache, which then will become invalid
//DebugLn('TListItems.ItemDestroying ',dbgs(AItem));
if (FCacheIndex <> -1) and (FCacheItem = AItem) then
idx := FCacheIndex
else
idx := FItems.IndexOf(AItem);
This line sets FCacheIndex
Item := ListView.Items[1];
Delete does not explicitly reset FCacheIndex, but obviously the cached item is no longer at index=1
If the listview has a handle, then it is reset here (lcl\include\customlistview.inc 265):
procedure TCustomListView.CNNotify(var AMessage: TLMNotify);
..
LVN_DELETEITEM: begin
Item := FListItems[nm^.iItem];
But clearly it is not save to rely on this.
This is also the cause for #22541 (closed)
Additional information:
procedure TForm1.Button1Click(Sender: TObject);
var
Item: TListItem;
ListView: TListView;
begin
ListView := TListView.Create(self);
Item := ListView.Items.Add;
Item := ListView.Items.Add;
Item := ListView.Items[1];
ListView.Items.Delete(0);
ListView.Items.Delete(0);
end;
Mantis conversion info:
- Mantis ID: 22552
- Version: 1.1 (SVN)
- Fixed in revision: 38145 (#25658113)