Delphi Programming

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

How to Move ListBox Items with the Mouse (Drag and Drop)

By Zarko Gajic, About.com

The TListBox Delphi component displays a collection of items in a scrollable list. Delphi makes it easy to program dragging and dropping into your applications.

Here's how to allow a user to rearrange (change item's position) the items of a ListBox using drag and drop:

  1. Drop a TListBox (named ListBox1) on a form
  2. Add several strings using the Items property
  3. Set ListBox1's DragMode to dmAutomatic (in Form's OnCreate or using Object Inspector at design-time).
  4. Handle LisBox-es MouseDown, DragOver and DragDrop events
var // form level
   StartingPoint : TPoint;

implementation

...

procedure TForm1.FormCreate(Sender: TObject) ;
begin
   ListBox1.DragMode := dmAutomatic;
end;

procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer) ;
var
   DropPosition, StartPosition: Integer;
   DropPoint: TPoint;
begin
   DropPoint.X := X;
   DropPoint.Y := Y;
   with Source as TListBox do
   begin
     StartPosition := ItemAtPos(StartingPoint,True) ;
     DropPosition := ItemAtPos(DropPoint,True) ;

     Items.Move(StartPosition, DropPosition) ;
   end;
end;

procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean) ;
begin
   Accept := Source = ListBox1;
end;

procedure TForm1.ListBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer) ;
begin
   StartingPoint.X := X;
   StartingPoint.Y := Y;
end;

Delphi tips navigator:
» How to Convert RGB Color to HSB (HSV) Color
« How to Detect a TPopupMenu's OnClose (OnPopDown) Event

More Delphi Programming Quick Tips

Explore Delphi Programming

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

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

Delphi Programming

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Using VCL Components
  5. TMouse
  6. How to Move ListBox Items with the Mouse (Drag and Drop) in Delphi application

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

All rights reserved.