Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 616
  • Last Modified:

How can I change the order of the Items in a ListView by drag and drop?

Hi,

I'd like to change the order of the Items in a ListView just by drag and drop with the mouse?
Is this possible?


thanks
0
Bohne
Asked:
Bohne
  • 2
1 Solution
 
shaneholmesCommented:
To drag items within a listview there are three things to do,
first set the dragmode in obect inspector to dmAutomatic.

In the OnDragOver event set the drag accept conditions, for example:

Procedure TForm1.ListView1DragOver(Sender, Source : TObject; X, Y :
Integer;
  State : TDragState; Var Accept : Boolean);
Begin
  Accept := (Source Is TListView)
        and (Source = Sender) // only accept from same  listview
End;

The list item manipulation code goes in the OnDragDrop event.
The following code will swap two items if one is dropped on the other
or put a dragged item at the end of the list if dropped on an empty
space.

Procedure TForm1.ListView1DragDrop(Sender, Source : TObject; X, Y :
Integer);
Var
  TargetItem, TempItem : TListItem;
Begin
  With TListView(Sender) Do
    Begin
      TempItem := items.add;
      TempItem.Assign(selected);
      TargetItem := GetItemAt(X, Y);
      If (TargetItem <> Nil) Then
        Begin
          selected.Assign(TargetItem);
          TargetItem.Assign(TempItem);
          TempItem.delete
        End
      Else
        selected.delete;
      Arrange(arAlignLeft)
    End;
End;

Shane
0
 
shaneholmesCommented:
If you want to do it at runtime by a click of a button (btnUp, btnDown), then the code:

btnUp:

 if  ListView1.ItemIndex <> 0 then
begin
 ListView1.ItemIndex:= ListView1.ItemIndex - 1;
 ListView1.Items[ListView1.ItemIndex].Selected:= True;
 ListView1.Items[ListView1.ItemIndex].Focused:= True;
end;

btnDown:

if  ListView1.ItemIndex <> ListView1.Items.Count - 1  then
begin
 ListView1.ItemIndex:= ListView1.ItemIndex + 1;
 ListView1.Items[ListView1.ItemIndex].Selected:= True;
 ListView1.Items[ListView1.ItemIndex].Focused:= True;
end;


Shane
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now