2010. április 18., vasárnap

Change the position of a list item in a TListView (3)


Problem/Question/Abstract:

I have a TListView object, and two buttons on a form. The ListView is populated with items all in one column, and I need to able to push one button to move the items up and the other button to move them down.

Answer:

Set ListView.HideSelection to false.

procedure MoveItems(AListView: TListView; Up: Boolean = True);
var
  OldItem, NewItem: TListItem;
  AIndex: Integer;
begin
  Assert(Assigned(AListView));
  with AListView do
  begin
    Items.BeginUpdate;
    try
      OldItem := TListItem.Create(Items);
      try
        OldItem.Assign(Selected);
        if Up then
          AIndex := Selected.Index - 1
        else
          AIndex := Selected.Index + 1;
        if not AIndex in [0..Items.Count - 1] then
          Exit;
        Selected.Delete;
        NewItem := Items.Insert(AIndex);
        NewItem.Assign(OldItem);
        Selected := NewItem;
      finally
        OldItem.Free;
      end;
    finally
      AListView.Checkboxes := False;
      Items.EndUpdate;
    end;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  MoveItems(ListView1, False);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  MoveItems(ListView1);
end;

Nincsenek megjegyzések:

Megjegyzés küldése