Drag and Drop from a TreeView to a ListBox 

In this this example, we'll drag and drop from a TreeView to a ListBox.  The example here has a TreeView with a main node called "Cars" which has subnodes that contains certain makes, and these in turn, have subnodes which contain specific models.  The ListBox is programmed to accept all the models if the "Cars' node is dragged and dropped, or all the models of a certain make if a certain "make" node is dragged and dropped.  The ListBox also accepts individually dragged models.  Both the ListBox and TreeView have DragMode properties set to dmAutomatic. 

KEYWORDS: drag and drop, BeginDrag, ClassNameIs, Node->GetNext 
 

 

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

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

    if (Sender->ClassNameIs("TListBox") && Source->ClassNameIs("TTreeView")) 
    { 
        //=== Dragging Cars (Top Node) ===// 
        if (TreeView1->Selected->AbsoluteIndex == 0) 
        { 
           TTreeNode *Node = TreeView1->Items->Item[0]->GetNext(); 
           while (Node != NULL) 
           { 
              if (Node->Level == 2) 
                  ListBox1->Items->Add(Node->Text); 
              Node = Node->GetNext(); 
           } 
        } 

        //=== Dragging a make ===// 
        if (TreeView1->Selected->Level == 1) 
        { 
            int count = 0; 
            TTreeNode *Node = TreeView1->Selected->GetNext(); 
            while (Node != NULL && Node->HasChildren == false) 
            { 
                ListBox1->Items->Add(Node->Text); 
                if (count < TreeView1->Selected->Count) Node = Node->GetNext(); 
                count ++; 
            } 
        } 

       //=== Dragging a model ===// 
       if (TreeView1->Selected->Level == 2) ListBox1->Items->Add(TreeView1->Selected->Text); 
     } 
}