Author: Tomas Rutkauskas
I have a TListView object, and two buttons on a form. The ListView is populated
with items all in one column, and I need to able to push one button to move the
items up and the other button to move them down.
Answer:
Set ListView.HideSelection to false.
1 2 procedure MoveItems(AListView: TListView; Up: Boolean = True);
3 var4 OldItem, NewItem: TListItem;
5 AIndex: Integer;
6 begin7 Assert(Assigned(AListView));
8 with AListView do9 begin10 Items.BeginUpdate;
11 try12 OldItem := TListItem.Create(Items);
13 try14 OldItem.Assign(Selected);
15 if Up then16 AIndex := Selected.Index - 1
17 else18 AIndex := Selected.Index + 1;
19 ifnot AIndex in [0..Items.Count - 1] then20 Exit;
21 Selected.Delete;
22 NewItem := Items.Insert(AIndex);
23 NewItem.Assign(OldItem);
24 Selected := NewItem;
25 finally26 OldItem.Free;
27 end;
28 finally29 AListView.Checkboxes := False;
30 Items.EndUpdate;
31 end;
32 end;
33 end;
34 35 procedure TForm1.Button1Click(Sender: TObject);
36 begin37 MoveItems(ListView1, False);
38 end;
39 40 procedure TForm1.Button2Click(Sender: TObject);
41 begin42 MoveItems(ListView1);
43 end;