Mirror

How to rearrange items within a TListBox (2) (Views: 708)


Problem/Question/Abstract:

I have a TListBox with, say, 10 strings, and I want to be able to use Drag and Drop to reorder those 10 items at runtime. How exactly do I do that?

Answer:

Here's the code I use to do list reordering. Create a new form, place a TListBox on it, set its DragMode property to dmAutomatic and connect the following event handlers.

procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer);
var
  aListBox: TListBox;
  DropIndex: Integer;
begin
  aListBox := Sender as TListBox;
  DropIndex := aListBox.ItemAtPos(Point(X, Y), False);
  if aListBox.ItemIndex < DropIndex then
    dec(DropIndex);
  aListBox.Items.Move(aListBox.ItemIndex, DropIndex);
  aListBox.ItemIndex := DropIndex;
end;

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

<< Back to main page