Rearranging ListView items using drag and drop 

Here's an example of rearranging items in a TListView, using the drag and drop method.  Be sure to set the DragMode propery of the ListView to dmManual... 

KEYWORDS:  drag and drop, BeginDrag, DragMode 
 
 

//---------------------------------------------------------------------------
//in source... 

//Begin the dragging on a mouse down event
void __fastcall TForm1::ListView1MouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) 

    //Be sure Sender can be converted into a TListView
    if (!dynamic_cast<TListView *>(Sender)) return

    //Convert Sender into a TListView
     TListView *DragListView = (TListView *)Sender; 

    //Begin the dragging process 
     DragListView->BeginDrag(0); 

//--------------------------------------------------------------------------------

void __fastcall TForm1::ListView1DragOver(TObject *Sender, TObject 
*Source, int X, int Y, TDragState State, bool &Accept) 

    //Check to see if the Control being dragged is 
     //indeed a ListView, and decide to accept the drop or not
    if (Source == Sender) Accept = true
    else Accept = false

//--------------------------------------------------------------------------------

void __fastcall TForm1::ListView1DragDrop(TObject *Sender, TObject 
*Source, int X, int Y) 

    //Find the (index) position of the mouse
    int NewItemIndex = ListView1->Items->IndexOf(ListView1->GetItemAt(X, Y)); 

    //Make NewItemIndex is within bounds
    if (NewItemIndex > -1 && NewItemIndex < ListView1->Items->Count) 
    { 
       //Insert a copy of the dragged item at the new location
        ListView1->Items->Insert(NewItemIndex); 
        ListView1->Items->Item[NewItemIndex] = ListView1->Selected; 

       //Delete the original 
        ListView1->Items->Delete(ListView1->Items->IndexOf(ListView1->Selected)); 
    }