Author: Mike Shkolnik
Exchange items in TListView
Answer:
Today I want to describe how you may exchange some items in standard TListView. For
example, you have 5 items and want to swap positions for first and third items
Problem that standard TListView component haven't such method and you must realize
it yourself.
We remember that the standard way from old Pascal times (for numbers) is:
1 procedure Swap(X, Y: Integer);
2 var3 s: Integer;
4 begin5 s := X;
6 X := Y;
7 Y := X
8 end;
Something similar we can do with TListItem too. But just to save all strings
(caption+sub items) somewhere is not enough because TListItem class have a lot of
other information (image indexes, pointer as Data, etc)
So correct way is to use Assign method:
9 10 procedure ExchangeItems(lv: TListView; const i, j: Integer);
11 var12 tempLI: TListItem;
13 begin14 lv.Items.BeginUpdate;
15 try16 tempLI := TListItem.Create(lv.Items);
17 tempLI.Assign(lv.Items.Item[i]);
18 lv.Items.Item[i].Assign(lv.Items.Item[j]);
19 lv.Items.Item[j].Assign(tempLI);
20 tempLI.Free;
21 finally22 lv.Items.EndUpdate
23 end;
24 end;
So structure is a same as in our sample for Integer. All what we added are
BeginUpdate and EndUpdate (just allow to reduce a flickering)
So if you want to exchange items in any ListView, just call this procedure...