unit UnitListBoxMover;

//
// corrected problems where moving an item would
// delete associated objects or associate objects with
// the wrong string
//
interface
uses ComCtrls, Classes, Contnrs, StdCtrls;

procedure MoveSelectedUp(lv : TListBox);
procedure MoveSelectedDown(lv : TListBox);
procedure MoveSelectedTop(lv : TListBox);
procedure MoveSelectedBottom(lv : TListBox);

implementation

procedure MoveSelectedUp(lv : TListBox);
var i : integer;
begin
    lv.Items.BeginUpdate;
    lv.Sorted := false;

    for i := 0 to (lv.Count - 1) do begin
        if (lv.selected[i]) and (i <> 0) then begin
            if (not lv.selected[i - 1]) then begin
                lv.Items.Exchange(i-1, i);
                lv.selected[i] := false;
                lv.selected[i - 1] := true;
            end;
        end;
    end;
    lv.items.endupdate;
end;

procedure MoveSelectedDown(lv : TListBox);
var i : integer;
begin
    lv.Items.BeginUpdate;
    lv.Sorted := false;

    for i := (lv.Count - 1) downto 0 do begin
        if (lv.selected[i]) and (i <> lv.count - 1) then begin
            if (not lv.selected[i + 1]) then begin
                lv.Items.Exchange(i+1, i);
                lv.selected[i] := false;
                lv.selected[i + 1] := true;
            end;
        end;
    end;

   lv.Items.EndUpdate;
end;

procedure MoveSelectedTop(lv : TListBox);
var i : integer;
begin
    lv.Items.BeginUpdate;
    //
    // the trick here is to move unselected items to the top
    //
    for i := 0  to (lv.items.count - 1) do begin
        if (lv.selected[i])  then begin
            lv.Items.Move(i,0);
            lv.selected[0] := true;
        end;
    end;

    lv.Items.EndUpdate;
end;

procedure MoveSelectedBottom(lv : TListBox);
var i: integer;
begin
    lv.Items.BeginUpdate;
    //
    // the trick here is to move unselected items to the top
    //
    for i := 0  to (lv.items.count - 1) do begin
        if (not lv.selected[i])  then begin
            lv.Items.Move(i, 0);
            lv.selected[0] := false;
        end;
    end;

    lv.Items.EndUpdate;
end;


end.
