Author: Jonas Bilinkevicius
How do I do drag and drop in a TListbox?
Answer:
Adding Drag and Drop facilities to a listbox is a matter of checking to see if
there is an item under the mouse pointer in the MouseDown event, and if so save the
item text and the index number to variables. Then check the MouseUp event to see if
there is a different item under the mouse. If so, delete the old item and insert a
copy of it in the new position.
Firstly, add three variables to the private section:
1 { Private declarations }2 Dragging: Boolean;
3 OldIndex: Integer;
4 TempStr: string;
5 6 //Then add the following code to the MouseUp and MouseDown events:7 8 procedure TForm1.ListBox1MouseUp(Sender: TObject; Button: TMouseButton;
9 Shift: TShiftState; X, Y: Integer);
10 var11 Index: integer;
12 begin13 if Dragging then14 begin15 Index := ListBox1.ItemAtPos(point(x, y), true);
16 if(Index > -1) and (Index <> OldIndex) then17 begin18 ListBox1.Items.Delete(OldIndex);
19 ListBox1.Items.Insert(Index, TempStr);
20 ListBox1.ItemIndex := Index;
21 end;
22 end;
23 Dragging := false;
24 end;
25 26 procedure TForm1.ListBox1MouseDown(Sender: TObject; Button: TMouseButton;
27 Shift: TShiftState; X, Y: Integer);
28 var29 Index: integer;
30 begin31 Index := ListBox1.ItemAtPos(point(x, y), true);
32 if Index > -1 then33 begin34 TempStr := ListBox1.Items[Index];
35 OldIndex := Index;
36 Dragging := true;
37 end;
38 end;