1. Home
  2. Computing & Technology
  3. Delphi Programming

Rearrange Multiple TListView Items using Drag and Drop

By Zarko Gajic, About.com

Rearrange Multiple Items in ListView

Rearrange Multiple Items in ListView

Using Delphi's drag and drop operations it is easy to implement rearranging multiple items in a TListView control.

Most MP3 (any multimedia) players allow arranging playlist using the technique provided below.

Drag and Drop Multiple Items Within a TListView

In the OnCreate event for the form, setup the ListView to allow multiple selection, change the view style to report, enable row selection and switch to automatic dragging.

In the OnDragOver for ListView, accept only if items belong to the ListView from where they originated, that is Source = Sender.

In the OnDragDrop iterate through all the selected items and change their position.

//Form.OnCreate
procedure TListViewForm.FormCreate(Sender: TObject) ;
begin
  ListView1.DragMode := dmAutomatic;
  ListView1.RowSelect := true;
  ListView1.MultiSelect := true;
  ListView1.ViewStyle := vsReport;
end;

//ListView OnDragDrop
procedure TListViewForm.ListView1DragDrop(Sender, Source: TObject; X, Y: Integer) ;
var
  currentItem, nextItem, dragItem, dropItem : TListItem;
begin
  if Sender = Source then
  begin
    with TListView(Sender) do
    begin
      dropItem := GetItemAt(X, Y) ;
      currentItem := Selected;
      while currentItem <> nil do
      begin
        nextItem := GetNextItem(currentItem, SdAll, [IsSelected]) ;
        if Assigned(dropItem) then
          dragItem := Items.Insert(dropItem.Index)
        else
          dragItem := Items.Add;
        dragItem.Assign(currentItem) ;
        currentItem.Free;
        currentItem := nextItem;
      end;
    end;
  end;
end;

//ListView OnDragOver
procedure TListViewForm.ListView1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean) ;
begin
  Accept := Sender = ListView1;
end;

Yes, that's it. The GetNextItem method returns the next selected item when the last parameter provided is IsSelected. The GetItemAt method returns the item where we want to drop all the selected ones.

Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Using VCL Components
  5. TListView
  6. Rearrange Multiple TListView Items using Drag and Drop in Delphi

©2009 About.com, a part of The New York Times Company.

All rights reserved.